父元素
嫌麻烦的看这一句话,在调用的方法外加
setTimeout(()=>{
this.$ref.xx.doWhat()
},0)
<template>
<div @click="a"></div>
<div v-if='show'>
<Children ref="youJump"><Children>
</div>
</template>
<script>
import Children from './components/Children'
export default{
components:{Children}
data(){
return{
show:false
}
}
methods:{
//错误方法
<!--原因:因为ref本身是作为渲染结果被创建的,在初始渲染的时候你不拿访问他们,他们还不存在,$refs也不是响应式的,因此你不应该试图用他们在模板中做数据绑定。-->
//a(){
//console.log(this.$refs.youJump) //undefined(因为DOM节点渲染问题)
//this.show=!this.show
//this.$refs.youJump.whatHappen()
//}
//√正确方法
a(){
this.show=!this.show
setTimeOut(()=>{
this.$refs.youJump.whatHappen()
},0);
}
},
// 第2种 ***判断有没有再使用nextTick***
a(){
if(this.$refs.sale){
this.$nextTick(()=> {
this.$refs.youJump.whatHappen()
})
}
}
}
</script>
子元素
<template>
<div></div>
</template>
<script>
export default:{
methods:{
whatHappen(){
console.log('IJump')
}
}
}
</script>
总结
- 原因:因为ref本身是作为渲染结果被创建的,在初始渲染的时候你不拿访问他们,他们还不存在,$refs也不是响应式的,因此你不应该试图用他们在模板中做数据绑定。