我有一个带有空模板的 Vue 组件,需要监听 prop 更改:
// component.vue
<template>
</template>
<script>
export default {
props: ['mode'],
updated: function() {
console.log('updated!')
}
}
</script>
//parent.vue
<template>
...
<childcomponent :mode="variable"></childcomponent>
</template>
...
现在只要 parent 的variable
变化,我期望 childcomponent.updated
被称为。然而,这似乎只有在子模板中使用该 Prop 时才会发生。
到目前为止,我想到的唯一解决方法是将子组件的模板设置为 <div v-show="false>{{ mode }}</div>
,但这似乎确实不对?有更好的方法来解决我的问题吗?
我首先使用空模板的原因是因为该组件与 js 库交互,该库本身执行大量 DOM 操作。
最佳答案
如果您不需要创建任何 DOM 元素,您可以watch
props 并使用空的 render
函数:
new Vue({
el: '#app',
data: {
word: ''
},
components: {
'child' : {
props: ['myprop'],
watch: {
myprop: function(n, o) {
console.log('changed to: ', n)
}
},
render: function(h) {
return h() // avoid warning message
}
}
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<child :myprop="word"></child>
<button @click="word = 'one'">One</button>
<button @click="word = 'two'">Two</button>
<button @click="word = 'three'">Three</button>
</div>
关于javascript - 没有模板的 vuejs react 性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751857/