咱們一般習慣在組件的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.