【发布时间】:2018-11-11 02:01:34
【问题描述】:
我刚遇到一个问题,如果一个组件只更新自己的数据,它不会触发父组件的指令的hook=componentUpdated。
正如Vue official Guide所说:
componentUpdated:在包含组件的 VNode 和 其子节点的 VNode 已更新。
似乎应该触发componentUpdated。
我做错了吗?还是误会了什么?
在下面的演示中,点击 Click Me! 按钮,您将看到 componentUpdated 未被调用。
但是当点击更改数据(与click me!执行类似的行为,不同的是它改变了父组件的数据),它会正确触发。
非常感谢。
Vue.config.productionTip = false
Vue.component('child', {
template: `<div>{{point}}
<span style="background-color:gray;font-weight:bold;color:red">
-{{mytest}}
</span>
<button @click="plusOne()">Click me!</button>
</div>`,
props: ['point'],
data(){
return {
mytest: 1
}
},
updated: function () {
console.log('updated component=child')
},
methods: {
plusOne() {
this.mytest += 1
}
}
})
let vMyDirective = {}
vMyDirective.install = function install (Vue) {
Vue.directive('my-directive', {
inserted: function () {
console.log('!!!directive for inserted')
},
bind: function bind (el, binding, vnode) {
console.log('!!!directive for bind')
},
componentUpdated: function componentUpdated (el, binding, vnode) {
console.log('!!!directive for component updated')
},
update: function () {
console.log('!!!directive for update')
}
})
}
Vue.use(vMyDirective)
new Vue({
el: '#app',
data() {
return {
testValues: ['label a', 'label b'],
testIndex: 1
}
},
methods:{
pushArray: function() {
this.testValues.push('label c')
},
changeData: function () {
this.testIndex += 1
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<button v-on:click="pushArray()">Add one Child!!!</button>
<button v-on:click="changeData()">Change Data - {{testIndex}}</button>
<div v-my-directive>
<child v-for="(item, index) in testValues" :key="index" :point="item"></child>
</div>
</div>
【问题讨论】:
-
好问题。显然这是非常值得成为new Vue Issue。在这种情况下,文档可能具有误导性。就像在 React 中一样,在 Vue 中,数据只有一种方式流动,即从父级到子级。如果这行得通,它可能会导致很多其他问题。
-
@JacobGoh 这可能是真的,如果是这样,可能指南应该使用准确的描述,如
componentUpdated: called after the containing component’s VNode and the VNodes of its children have been remounted.
标签: javascript vue.js vuejs2