咱们一般习惯在组件的mounted阶段对要显示的数据进行必定的处理而后渲染页面。可是子组件在其mounted阶段没法获取父组件的异步数据以及父组件的mounted所建立的数据。vue
为这些数据在子组件中设置watch。当数据更新时将触发操做。bash
//vue父子组件间的数据传输-问题一:
父组件mounted中建立的数据或异步数据,子组件mouted中没法得到
// 子组件
Vue.component('child',{
template:'<h1>child</h1>',
props:['object','asyncData'],
mounted () {
console.log('child mounted object',this.object) // null
console.log('child mounted asyncData',this.asyncData) // null
},
// 解决方案:添加watch
watch: {
object (newOb) {
console.log('child watch object',nob)
},
asyncData (newData) {
console.log('child watch asyncData',ndata)
}
}
})
// 父组件
new Vue({
el: '#app',
template: `
<div id='parent'>
<child :object='object' :asyncData='asyncData'></child>
</div>
`,
data: {
object: null,
asyncData: null
},
mounted () {
setTimeout(() => this.asyncData = 'asyncData',1000)
this.object = {age :18}
}
})
复制代码
See the Pen
vue父子组件间的数据传输-问题一 by madman0621 (
@madman0621) on
CodePen.
子组件设置watch监听父组件传输来的数据对象,可是当父组件改变数据对象中的某一个值时,子组件的watch并不会触发。app
子组件设置watch监听父组件传输来的数据对象时,只有当这个数据对象setter时才会触发子组件的watch,即只有给这个数据对象从新赋值才会触发子组件的watch,若是仅仅是修改数据对象中的某个属性,不会触发子组件的watch。异步
为子组件的watch添加deep:true属性async
// 子组件设置watch监听父组件传输来的数据对象,
可是当父组件改变数据对象中的某一个值时,子组件的watch并不会触发。
// 子组件
Vue.component('child',{
template:'<h1>{{ age }}</h1>',
props:['object'],
data () {
return {
age : null
}
},
watch: {
object: {
//解决方案
deep:true,
handler (nob) {
this.age = nob.age
}
}
}
})
// 父组件
new Vue({
el: '#app',
template: `
<div id='parent'>
<child :object='object'></child>
<button @click='change'>改变父组件的object</button>
</div>
`,
data: {
object: null
},
mounted () {
this.object = {age: 18}
},
methods: {
change () {
this.object.age = 20
}
}
})
复制代码
See the Pen
vue父子组件间的数据传输-问题二 by madman0621 (
@madman0621) on
CodePen.