使用场景:在vue项目中,父子组件之间的通信是很常见也是我们熟悉的,但祖孙组件是如何通信的呢?-----》通过provide/inject可以轻松实现跨级访问祖先组件的数据
下面以一个孙组件调用组件组件刷新页面方法为例:
祖先组件----》App.vue:
<template>
<div id="app">
<router-view v-if="isRouterAlive"/>
</div>
</template>
<script>
export default {
name: 'App',
provide(){
return {
reload:this.reload
}
},
data(){
return {
isRouterAlive:true
}
},
methods:{
reload(){
this.isRouterAlive = false;
this.$nextTick(function(){
this.isRouterAlive = true;
})
}
}
}
</script>
孙组件------》list.vue:
<template>
<div class="list">
<el-button type="success" @click="toClick">点我刷新页面</el-button>
</div>
</template>
<script>
export default {
inject:['reload'],
methods:{
toClick(){
this.reload()
}
}
}
</script>