vue3.0父子组件的通信

vue3.0父子组件的通信

Vue3.0组件通信

vue3.0脚手架setup内部的组件通信

1、父到子通过props

父组件

<template>
  <div >
    <Son data="currentRole.arr"></Son>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive} from "vue";
import Son from "../components/Son.vue";

export default defineComponent({
  name: "father",
  components: { Son },
  setup() {
     let currentRole = reactive({
      arr: [{name:"小王",age:21}],
    }); 
    return { currentRole};
  },
});
</script>

子组件

<template>

</template>

<script lang="ts">
import { onMounted } from "vue";
export default defineComponent({
 props: {
    data: {},
  },
  setup() {
    const getData = () => {
      console.log("传递的参数", props.data);
    };
    onMounted(() => {
      getData ();
    });
  },
});
</script>

2、父到子通过provide和inject
父组件

<template>
   <div >
    <Son ></Son>
  </div>
</template>

<script lang="ts">
import { provide, ref } from "vue";
import Son from "../components/Son.vue";

export default defineComponent({
  name: "father",
  components: { Son },
  setup() {
    provide("customVal", "我是父组件向子组件传递的值");
  },
});
</script>

子组件

<template>
  <div>
    <h1>{{ customVal}}</h1>
  </div>
</template>

<script lang="ts">
import { inject, ref } from "vue";
export default defineComponent({
  setup() {
    const customVal = inject("customVal");
    return { customVal,};
  },
});
</script>

3、父组件调用子组件的方法
父组件

<template>
  <div >
    <Son ref="RefChilde"></Son>
    <div  @click="fnCallChild">
      点我调用Son组件里的方法
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import Son from "../components/Son.vue";

export default defineComponent({
  name: "father",
  components: { Son },
  setup() {
    const RefChilde = ref();     //RefChilde 要和Son组件上的class名相同
    const fnCallChild = () => {
      RefChilde.value.sonFn();      //sonFn是子组件里的方法
    };
    return { RefChilde, fnCallChild };
  },
});
</script>

子组件

<template>
  <div>
    <h1>{{ conts }}</h1>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
  setup() {
    const conts = ref("我是子组件");
    const sonFn = () => {
      conts.value = "我被父组件里调用了子组件的方法修改了数据";
    };
    return { conts, sonFn };
  },
});
</script>

上一篇:filebeat 修改导入进入 elasticsearch 的索引名


下一篇:Python安装本地第三方包 pip install -e