我对 Vue.js 还很陌生,到目前为止我很喜欢它。我只有一个问题:如何渲染字符串和字符串中的内容? 例如:
//…
data:{
string:"hi, {{name}}",
name:"John Doe"
}
{{string}}<!—won’t work —>
<span v-html="string"></span><!—neither this —>
我想在 html 中插入“字符串”,后缀插入“名称”。
“Hello {{name}}”应该插入在 Ajax 调用之后,因此不会出现在 HTML 中。
输出应该是“hi, John Doe”。
说清楚,我想要的是:
{{string}}
<!-- becomes-->
hi, {{name}}
<!--finally becomes-->
hi, John Doe
答案 0 :(得分:1)
使用计算属性返回字符串中包含数据变量的字符串;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="app">
<h1>{{this.stringWithVar}}</h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
name: 'John Doe'
},
computed: {
stringWithVar: function () {
return `hi, ${this.name}`;
}
}
})
</script>
</body>
</html>