提供、注入はコンポーネント通信の方法でもあり、親コンポーネントが他の子コンポーネントや孫と通信する方法でもあります
親コンポーネント、father.vue
<template>
<div>
<children />
</div>
</template>
<script>
import children from './children/children'
export default {
data() {
return {
aa: "ss",
};
},
components:{
children
},
provide(){
return {
father:this
}
},
methods: {
log(){
console.log('哈哈')
}
},
};
</script>
サブアセンブリ
<template>
<div @click="dianji()">
{
{name}}
<grandSon />
</div>
</template>
<script>
import grandSon from './grandchild/grandchild'
export default {
inject:['father'],
components:{
grandSon
},
computed:{
name(){
return this.father.aa
}
},
methods: {
dianji(){
this.father.log()
}
},
}
</script>
サンコンポーネント
<template>
<div class="grandchild">
<ul @click="dianji">
<li>{
{name}}</li>
</ul>
</div>
</template>
<script>
export default {
inject:['father'],
computed:{
name(){
return this.father.aa
}
},
methods: {
dianji(){
this.father.log()
}
},
}
</script>
子コンポーネントと孫コンポーネントの両方が、父コンポーネントのデータとメソッドを取得して使用できます