对组件 DOM 没有影响的 prop 更改会触发其 updated
功能,出乎意料。
https://jsfiddle.net/e5gyuorL/1/
v-html="markup()"
的结果相同或{{markup()}}
或computed: { markup: ... }
.
updated
的文档( https://v2.vuejs.org/v2/api/#updated ) 说:
Called after a data change causes the virtual DOM to be re-rendered and patched.
如何捕获实际的 DOM 重新渲染?如果这是常见问题解答,请道歉;我看了长度。
最佳答案
我能想到的最直接的方法是让组件将其 innerHTML
存储在数据项中,并在每次更新时检查它是否已更改:
Vue.component('t-markdown', {
template: '#t-markdown',
data: {
innerHTML: ''
},
props: {src:String},
methods: {
markup: function() { return this.src.slice(0,11) },
},
updated: function() {
if (this.innerHTML !== this.$el.innerHTML) {
this.$parent.count++;
this.innerHTML = this.$el.innerHTML;
}
},
mounted() {
this.innerHTML = this.$el.innerHTML;
}
});
new Vue({
el: "#app",
data: {count:0, inp:'<b>src</b> '},
methods: {
change: function() { this.inp += '#' },
},
mounted() {
setTimeout(() => this.inp = '<i>changed!</i>', 7000);
}
})
body {
background: #20262E;
padding: 20px;
font-family: sans-serif, Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<t-markdown :src="inp"></t-markdown>
<button @click="change">change</button> updated: {{count}}
<div>
{{inp}}
</div>
</div>
<script type="text/x-template" id="t-markdown">
<div v-html="markup()"></div>
</script>
关于javascript - 组件 DOM 更改时的 Vue 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728881/