vue3 组件通信 --- useAttrs()

3,706 阅读1分钟

本篇讲的是使用 useAttrs() 实现父传子,该方法可以将父组件中子组件标签身上的属性和属性值传递给子组件内部,且可以获取自定义事件。

Parent.vue

<template>
  <div>我是父组件</div>
  <hr />
  <Child title="hello" data="123" @abc="handler" color="red"></Child>
</template>

<script setup>
import Child from "./Child.vue";

const handler = () => {
  alert(666);
};
</script>

Child.vue

<template>
  <div>
    <h1 :title="title">我是子组件的内容</h1>
    <button :="$attrs" :style="`color: ${$attrs.color}`" @click="$attrs.onAbc()">
      我是子组件的按钮
    </button>
  </div>
</template>

<script setup>
// useAttrs 可以获取标签身上的属性与属性值,还可以获取自定义事件
// 如果使用 defineProps 拿到属性,那么使用 $attrs 就获取不到该属性了,defineProps 比 $attrs 优先级高
import { useAttrs } from "vue";

const $attrs = useAttrs();
// 使用 defineProps 此时 $attrs 里没有 title 属性了
defineProps(['title'])
</script>

因为 title 被 defineProps 接收了,所以这里 $attrs 已经没有了。

image.png

总结:

useAttrs() 返回一个 Proxy 对象,内容为子组件标签身上的属性和方法。