vue3 父子组件传递事件和方案

83 阅读1分钟

个人学习笔记保存,写不来文章供大家学习,因此自己看的懂就行,误入来的朋友勿喷。

父组件

<script setup lang="ts">
import { ref } from "vue";
import Child from "./Child.vue";
import type { Persons } from "../types/Person";

const personList = ref<Persons>([
  {
    name: "小张老师",
    age: 18,
    id: 1,
  },
  {
    name: "小红老师",
    age: 20,
    id: 2,
  },
]);

const message = ref("我是来自 父组件数据");

const getChildMessage = (value: string) => {
  alert(`来自子组件回调方法: ${value}`);
};

const bindEventFun = (value: string) => {
  alert(`子组件绑定事件: ${value}`);
};
</script>

<template>
  <div class="father">
    <div>父控件 message: {{ message }}</div>
    <Child
      :list="personList"
      :title="message"
      :getMessage="getChildMessage"
      @bindEvent="bindEventFun"
    />
  </div>
</template>

<style lang="scss" scoped>
.father {
  display: flex;
  flex-direction: column;
  background-color: brown;
  padding: 30px;
  font-style: italic;
  color: #ffffff;
}
</style>

子组件

<script setup lang="ts">
import { withDefaults } from "vue";
import type { Persons } from "../types/Person";

/**
 * 定义只是接收
 */
defineProps<{
  list?: Persons;
  title: string;
  getMessage: (vlaue: string) => void;
}>();

/**
 * 定义可传入默认值
 */
// withDefaults(
//   defineProps<{
//     list?: Persons;
//     title: string;
//     getMessage: (vlaue: string) => void;
//   }>(),
//   {
//     list: () => [
//       {
//         name: "冠希哥",
//         age: 28,
//         id: 1,
//       },
//     ],
//     title: "默认值",
//   }
// );

/**
 * 提供子组件绑定事件
 */
const emit = defineEmits(["bindEvent"]);
</script>

<template>
  <div class="child">
    <div>父组件传入的数据: {{ title }}</div>
    <div v-for="item in list" :key="item.id">
      <div>姓名:{{ item.name }} 年龄:{{ item.age }}</div>
    </div>
    <button
      style="padding: 30px"
      hover-class="button-hover"
      @click="getMessage('方法回调父控件')"
    >
      方法方式调用 父组件
    </button>
    <button
      style="padding: 30px"
      hover-class="button-hover"
      @click="emit('bindEvent', '事件绑定回传父组件')"
    >
      事件方式调用 父组件
    </button>
  </div>
</template>

<style lang="scss" scoped>
.child {
  background-color: rgb(193, 127, 255);
  padding: 30px;
  margin-top: 30px;
}
</style>

使用$attrs实现祖孙数据传递

image.png