vue3 组件通信 --- ref & $parent

2,964 阅读1分钟

该文章讲的是父子通信,父组件通过 ref 获取子组件的属性,子组件通过 $parent 获取父组件的属性。同时,由于组件内部数据默认是只能组件内部自己访问,所以想让外部访问到必须使用 defineExpose() 方法对外暴露。当然了,获取方法也和获取数据同理。

ref

Parent.vue

<template>
  <div>
    <h1>我是父组件 {{ count }}</h1>
    <button @click="handler">加10</button>
    <hr />
    <!-- 给子组件身上绑定 ref -->
    <Child1 ref="child1"></Child1>
  </div>
</template>

<script setup>
import { ref } from "vue";
import Child1 from "./Child1.vue";

let count = ref(100);
// 获取子组件的实例
let child1 = ref()

const handler = () => {
    count.value += 10;
    // 获取子组件的数据
    child1.value.count += 10
};
</script>

Child1.vue

<template>
    <div>
        <h2>我是子组件1 {{ count }}</h2>
    </div>
</template>

<script setup> 
import { ref } from 'vue'

let count = ref(10)

// 组件内部的数据默认对外是关闭的,只能内部使用,如果想让外部访问,要使用该方法对外暴露
defineExpose({ count })
</script>

$parent

Parent.vue

<template>
  <div>
    <h1>我是父组件 {{ count }}</h1>
    <button @click="handler">加10</button>
    <hr />
    <Child2></Child2>
  </div>
</template>

<script setup>
import { ref } from "vue";
import Child2 from "./Child2.vue";

let count = ref(100);

defineExpose({ count })
</script>

Child2.vue

<template>
    <div>
        <h2>我是子组件2 {{ count }}</h2>
        <button @click="handler($parent)">加 10</button>
    </div>
</template>

<script setup> 
import { ref } from 'vue'

let count = ref(10)

const handler = ($parent) => {
    count.value += 10
    $parent.count += 10
}

总结

  • ref 获取子组件实例,想要获取子组件的属性和方法,子组件内部使用 defineExpose() 对外暴露即可,使用时调用 ref.value.xxx
  • $parent 获取父组件实例,想要获取父组件的属性和方法,父组件内部使用 defineExpose() 对外暴露即可,使用时调用 $parent.xxx