这个问题类似于VueJS re-compile HTML in an inline-template component同时也How to make Vue js directive working in an appended html elementVueJs操纵联模板,并对其进行重新初始化
不幸的是在这个问题的解决不能再对当前VueJS执行情况$compile
使用已被删除。
我的使用情况如下:
我不得不使用它操作的页面,之后触发一个事件的第三方代码。现在事件被解雇后,我想让VueJS知道它应该重新初始化当前的DOM。
(这是写在纯JavaScript第三方允许用户将新的小部件添加到页面)
https://jsfiddle.net/5y8c0u2k/
HTML
<div id="app">
<my-input inline-template>
<div class="wrapper">
My inline template<br>
<input v-model="value">
<my-element inline-template :value="value">
<button v-text="value" @click="click"></button>
</my-element>
</div>
</my-input>
</div>
使用Javascript - VueJS 2.2
Vue.component('my-input', {
data() {
return {
value: 1000
};
}
});
Vue.component('my-element', {
props: {
value: String
},
methods: {
click() {
console.log('Clicked the button');
}
}
});
new Vue({
el: '#app',
});
// Pseudo code
setInterval(() => {
// Third party library adds html:
var newContent = document.createElement('div');
newContent.innerHTML = `<my-element inline-template :value="value">
<button v-text="value" @click="click"></button>
</my-element>`; document.querySelector('.wrapper').appendChild(newContent)
//
// How would I now reinialize the app or
// the wrapping component to use the click handler and value?
//
}, 5000)
新代码可以显示在网页上的任何位置吗? –
是的,有多个地点是动态生成的。我找到了一个解决方案,但感觉更像是一个黑客:https://jsfiddle.net/9ukmy0k0/ – jantimon
琐事是不可避免的:你违反与Vue的合同,它将控制DOM。 –