常用的方法就不写了,主要分享下provide/inject(提供/注入)的方法
可以实现跨层组件(祖孙)间通信,不需要将数据一层一层向下传递

//父组件 Father.vue
<template>
  <son></son>
</template>
<script>
 import { defineComponent, reactive, provide, computed } from "vue";
 import son from "@/components/Son";
 export default defineComponent({
  components: {
    son
  },
  setup() {
   let params = reactive({
      name: "来自父亲的参数"
   })
   provide("name", computed(()=> params.name)); //用计算属性返回值能够动态传递来子/孙组件(当子孙组件通过方法触发修改name值时)
   function changeName(val){
     params.name = val; //子孙组件触发
   }
   provide("changeName",changeName);
  }
 })
</script>
//儿子组件 Son.vue
<template>
  <h2>{{ name }}</h2>  
  <button @click="changeName('儿子组件触发')">儿子组件触发Name修改</button>
  <div class="grandson">
    <grandson></grandson>
  </div>
</template>
<script>
import grandson from "@/components/grandson";
import { defineComponent, inject } from "vue";
export default defineComponent({
  components: { grandson },
  setup() {
    let name = inject("name");  //接收Father组件传来的name
    let changeName = inject("changeName"); //接收方法
    return {
      name,
      changeName,
    };
  },
});
</script>
//孙子组件 grandson.vue
<template>
  <h2>{{ name }}</h2>
  <button @click="changeName('孙子组件触发')">孙子组件触发Name修改</button>
</template>
<script>
import { defineComponent, inject, watch } from "vue";
export default defineComponent({
  name: "HelloWorld",
  setup() {
    let name = inject("name");
    let changeName = inject("changeName");
    watch(name,(newValue,oldValue)=>{
      //这里可以监听name的变化
    })
    return {
      name,
      changeName,
    };
  },
});
</script>

子孙组件都接收到Father组件传来的参数"来自Father组件的参数"。
当点击儿子组件或者孙子组件按钮时,触发changeName事件在Father组件上name值也会改变。

Logo

前往低代码交流专区

更多推荐