vue父组件传递值给子组件
子组件
<template>
<div>{{parentMsg}}</div>
</template>
<script>
export default{
data(){
return {
parentMsg:''
}
},
methods:{
getMsg(msg){
this.parentMsg = msg;
}
}
}
</script>
父组件
<template>
<div>
<child-comp ref="child"></child-comp>
<button @click="sendMsg">SEND MESSAGE</button>
</div>
</template>
<script>
import childComp from 'path'
export default{
components:{
childComp
},
methods:{
sendMsg(){
this.$refs.child.getMsg('Parent Message');
}
}
}
</scritp>
这样调用可能存在异常,子组件为被加载出来,就调用了子组件的方法
TypeError :Cannot read properties of undefined
需要在父组件调用的时候加上 $nextTick 方法,等待子组件加载之后调用
改造后代码:
<template>
<div>
<child-comp ref="child"></child-comp>
<button @click="sendMsg">SEND MESSAGE</button>
</div>
</template>
<script>
import childComp from 'path'
export default{
components:{
childComp
},
methods:{
sendMsg(){
this.$nextTick( () => {
this.$refs.child.getMsg('Parent Message');
} )
}
}
}
</scritp>