vue3 组件间通信

103 阅读1分钟

父子组件之间通信

父传子

props、attrs

parent.vue

<template>
  <div>
    <h1>parent</h1>
    <hr />
    <children-1
      v-model:count="count"
      :list="list"
      title="winy"
    ></children-1>
  </div>
</template>

<script setup lang="ts">
import { ref } from "@vue/reactivity";
import children1 from "./component/children1.vue";
import children2 from "./component/children2.vue";

interface List {
  label: string;
  value: string;
}
const count = ref<number>(10);
const list = ref<List[]>([
  {
    label: "name",
    value: "winy",
  },
  {
    label: "age",
    value: "18",
  },
]);
</script>

children1.vue

import { ref, useAttrs } from "vue";

interface List {
  label: string;
  value: string;
}
interface FatherData {
  count: number;
  list: List[];
}

const props = withDefaults(defineProps<FatherData>(), {
  count: 20,
  list: () => [
    {
      label: "default",
      value: "default",
    },
  ],
});

const attrs = useAttrs();
console.log(attrs.title);

子传父

emit

parent.vue

    <children-1
      v-model:count="count"
      :list="list"
      title="winy"
      @sendMessage="receiveMessage"
    ></children-1>
    
    
    const receiveMessage = (e: string) => {
      console.log(e);
    };

children1.vue

type ToFather = {
  (e: "sendMessage", value: string): void;
  (e: "update:count", value: number): void;
};
const message = "children1 message";

const emit = defineEmits<ToFather>();
const sendTOFather = () => {
  emit("sendMessage", message);
//   emit("update:count", 20);
};

跨组件通信

provide/inject

component1.vue

import { provide } from "vue";

provide("name", "winy ww");

component2

import { inject } from "vue";

const name = inject("name");
console.log(name);

pinia

前面有讲到pinia的基本使用,直接上链接:juejin.cn/post/714535…

小结

组件之间的通信当然不止前面所说到的,比如还有mitt、expose这些,用的相对少一些我就没有整理,我只把我开发中用到的用的多的整理出来供大家参考!谢谢大家!