你可以在 Vuejs 的模板字符串中动态定义属性吗? [英] Can you dynamically define properties in a template string in Vuejs?
问题描述
我可以传入一个模板字符串并动态传入一个属性,以便我可以使其具有反应性吗?在下面的示例中,我希望消息具有反应性,但我不想在 data 选项上预先定义它.
<component :is="string && {template:string}"/>新的 Vue({el:'#vue',数据(){返回 {字符串:未定义,}},创建(){//setTimeout 模拟ajax调用setTimeout(()=> this.string = '<div><h1 v-for="n in 1">Hello! </h1><input v-model="message" placeholder="编辑我"><p>消息是:{{消息}}</p></div>', 1000)}})
https://jsfiddle.net/kxtsvtro/5/
您可以像指定模板一样指定 data
:只需将其插入到组件规范中即可.
new Vue({el: '#vue',数据() {返回 {字符串:未定义,数据对象:未定义}},创建(){//setTimeout 模拟ajax调用setTimeout(() => {this.string = '<div><h1 v-for="n in 1">Hello!</h1><input v-model="message" placeholder="edit me"><p>消息是:{{消息}}</p></div>';this.dataObj = {消息:'初始'};}, 1000)}})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script><div id="vue"><component :is="string && {template:string, data: function() { return dataObj}}"/>
Can I pass in a template string and also dynamically pass in a property so that I can make it reactive? In the example below I would like message to be reactive, but I don't want to have to predefine it on the data option.
<div id="vue">
<component :is="string && {template:string}"/>
</div>
new Vue({
el:'#vue',
data(){
return {
string:undefined,
}
},
created(){
//setTimeout to simulate ajax call
setTimeout(()=> this.string = '<div><h1 v-for="n in 1">Hello! </h1><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p> </div>', 1000)
}
})
https://jsfiddle.net/kxtsvtro/5/
You can specify the data
in the same way you specify the template: just interpolate it into the component spec.
new Vue({
el: '#vue',
data() {
return {
string: undefined,
dataObj: undefined
}
},
created() {
//setTimeout to simulate ajax call
setTimeout(() => {
this.string = '<div><h1 v-for="n in 1">Hello!</h1><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p></div>';
this.dataObj = {
message: 'initial'
};
}, 1000)
}
})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="vue">
<component :is="string && {template:string, data: function() { return dataObj}}" />
</div>
这篇关于你可以在 Vuejs 的模板字符串中动态定义属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!