gpt4 book ai didi

variables - VueJS - 在字符串中插入字符串

转载 作者:行者123 更新时间:2023-12-04 15:55:04 26 4
gpt4 key购买 nike

在 VueJS 中,有没有办法在模板或脚本中将字符串插入字符串?例如,我希望以下内容显示 1 + 1 = 2 而不是 1 + 1 = {{ 1 + 1 }}

<template>
{{ myVar }}
</template>

<script>
export default {
data() {
"myVar": "1 + 1 = {{ 1 + 1 }}"
}
}
</script>

编辑:为了更好地说明我为什么需要这个,下面是我的实际数据:

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 将由用户定义。虽然我可以将问题属性重建为计算属性,但我宁愿保持现有数据结构不变。

最佳答案

我从 https://forum.vuejs.org/t/evaluate-string-as-vuejs-on-vuejs2-x/20392/2 找到了我正在寻找的解决方案,它提供了一个关于 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>

关于variables - VueJS - 在字符串中插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52062680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com