更新:
基于
this answer,您可以在Vue 2中执行类似的动态模板组件.您实际上可以在计算部分中设置组件规范并使用
:is绑定它
var v = new Vue({
el: '#vue',
data: {
message: 'hi #linky'
},
computed: {
dynamicComponent: function() {
return {
template: `
${this.hashTags(this.message)} `,methods: {
someAction() {
console.log("Action!");
}
}
}
}
},
methods: {
hashTags: function(value) {
// Replace hash tags with links
return value.replace(/#(\S*)/g, '#$1')
}
}
});
setTimeout(() => {
v.message = 'another #thing';
}, 2000);
内插HTML不会发生Vue绑定.你需要一些Vue看作模板的东西,比如a partial.但是,Vue只将绑定应用于部分一次;您无法返回并更改模板文本并重新绑定.因此,每次模板文本更改时,您都必须创建一个新的部分.
有一个您可以在HTML中添加标记/元素,并且它接受变量名称,因此过程为:
>模板HTML更改
>为新模板HTML注册新的部分名称
>更新名称变量,以便呈现新的部分
每次有变化时注册新内容都有点可怕,所以如果可能的话,最好使用具有更结构化模板的组件,但如果你真的需要带有绑定的完全动态HTML,它就可以工作.
下面的示例以一条消息开始,根据您的过滤器进行链接,并在两秒后更改消息.
您可以使用message作为部分名称进行注册,但是您需要一个在执行注册后返回该名称的computed,否则它将尝试在注册名称之前呈现.
var v = new Vue({
el: 'body',
data: {
message: 'hi #linky'
},
computed: {
partialName: function() {
Vue.partial(this.message, this.hashTags(this.message));
return this.message;
}
},
methods: {
someAction: function() {
console.log('Action!');
},
hashTags: function(value) {
// Replace hash tags with links
return value.replace(/#(\S*)/g, '#$1')
}
}
});
setTimeout(() => {
v.$set('message', 'another #thing');
}, 2000);
更多推荐
vue动态生成html元素,Vue.js中的动态html元素
发布评论