我可以传入一个模板字符串,也可以动态地传入一个属性,这样我就可以让它成为响应式的吗?在下面的示例中,我希望消息是响应式的,但我不想在数据选项上预定义它。
<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)
}
})发布于 2018-02-16 01:57:29
您可以使用与指定模板相同的方式指定data:只需将其插入到元件规范中即可。
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>
发布于 2018-02-16 01:37:17
您可以使用Props,但我不确定这是否是最好的方法:)下面是一个示例:
new Vue({
el:'#vue',
data(){
return {
string:undefined,
message:''
}
},
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)
}
})<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script>
<div id="vue">
<component :is="string && {template:string, props:['message']}" :message="message"/>
</div>
发布于 2018-02-16 04:14:14
看起来您需要的是一个具有<slot>的组件,您可以将自定义组件转储到该组件中。如果您正在尝试编写组件,这可能是最简单的方法。
https://stackoverflow.com/questions/48812822
复制相似问题