Vue项目provide和inject的使用

provide,inject也是组件通信的一种方式,它是父组件向其他子组件,孙组件通信的一种方式

父组件,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>

子组件和孙组件都可以获取和使用到father组件里面的数据和方法

猜你喜欢

转载自blog.csdn.net/weixin_45389051/article/details/114698518