VueJS-在字符串中插入字符串 [英] VueJS - Interpolate a string within a string
问题描述
在VueJS中,是否可以在模板或脚本中在字符串内插入字符串 ?例如,我希望以下内容显示1 + 1 = 2
而不是1 + 1 = {{ 1 + 1 }}
.
In VueJS, is there a way to interpolate a string within a string, either in the template or in the script? For example, I want the following to display 1 + 1 = 2
instead of 1 + 1 = {{ 1 + 1 }}
.
<template>
{{ myVar }}
</template>
<script>
export default {
data() {
"myVar": "1 + 1 = {{ 1 + 1 }}"
}
}
</script>
为了更好地说明为什么我需要这样做,这是我的实际数据:
to better illustrate why I would need this, here's what my actual data looks like:
section: 0,
sections: [
{
inputs: {
user: {
first_name: {
label: "First Name",
type: "text",
val: ""
},
...
},
...
},
questions: [
...
"Nice to meet you, {{ this.section.inputs.user.first_name.val }}. Are you ...",
...
]
},
...
],
this.section.inputs.user.first_name.val
将由用户定义.虽然我可以将问题属性重建为计算属性,但我希望保持现有的数据结构不变.
this.section.inputs.user.first_name.val
will be defined by the user. While I could rebuild the question properties as computed properties, I would rather keep the existing data structure in tact.
推荐答案
我从 https://jsfiddle.net/cpfarher/97tLLq07/3/
I found the solution I was looking for from https://forum.vuejs.org/t/evaluate-string-as-vuejs-on-vuejs2-x/20392/2, which provides a working example on JsFiddle: https://jsfiddle.net/cpfarher/97tLLq07/3/
<template>
<div id="vue">
<div>
{{parse(string)}}
</div>
</div>
</template>
<script>
new Vue({
el:'#vue',
data:{
greeting:'Hello',
name:'Vue',
string:'{{greeting+1}} {{name}}! {{1 + 1}}'
},
methods:{
evalInContext(string){
try{
return eval('this.'+string)
} catch(error) {
try {
return eval(string)
} catch(errorWithoutThis) {
console.warn('Error en script: ' + string, errorWithoutThis)
return null
}
}
},
parse(string){
return string.replace(/{{.*?}}/g, match => {
var expression = match.slice(2, -2)
return this.evalInContext(expression)
})
}
}
})
</script>
这篇关于VueJS-在字符串中插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!