vue3探索——使用ref与$parent实现父子组件间通信

发布时间 2023-09-05 21:54:28作者: 前端cry

在vue3中,可以使用vue3的API defineExpose()函数结合ref或者$parent,实现父子组件数据的传递。

子组件向父组件传递数据defineExpose()ref

  • 子组件:通过defineExpose() 函数,向外暴露响应式数据或者方法
// src/components/son.vue
<template>
    <div>
        <h1>儿子有 ${{ son_money }}</h1>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

// 1-定义子组件内部的响应式数据
const son_money = ref(500);

// 2-定义子组件内部的方法
function queryMoney() {
    alert('儿子还有 $' + son_money.value);
}

// 3-重点:把子组件中的数据或者方法暴露出去
defineExpose({
    son_money,
    queryMoney
});
</script>
  • 父组件:通过ref获取子组件实例,进而获取子组件暴露的响应式数据或方法
// src/App.vue
<template>
    <div>
        <h1>父组件</h1>
        <button @click="querySon">看看儿子有多少钱</button>
        <button @click="giveSon">给儿子打50块钱</button>
        <hr>
        <!-- 2-使用子组件 -->
        <Son ref="son" />
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
// 1-引入子组件
import Son from './components/son.vue';

// 3-获取子组件的实例
const son = ref();

function querySon() {
	// 4-重点:调用子组件暴露的 queryMoney()方法
    son.value.queryMoney();
}

function giveSon() {
	// 5-重点:查改子组件暴露的数据 son_money
    son.value.son_money += 50;
}
</script>

? 你没看错!这里的ref就是经常用来定义响应式数据的那个ref ,所以在script 标签中使用,需要带上.value

ref 的两个作用:

  • 定义响应式数据
  • 获取子组件实例

父组件向子组件传递数据defineExpose()$parent

  • 父组件:通过defineExpose() 函数,向外暴露响应式数据或者方法
// src/App.vue
<template>
    <div>
        <h1>父组件有 ${{ money }}</h1>
        <hr>
        <!-- 2-使用子组件 -->
        <Daughter />
    </div>
</template> 

<script setup lang="ts">
import { ref } from 'vue';

// 1-引入子组件
import Daughter from './components/daughter.vue';

// 3-定义父组件响应式数据
const money = ref(1000);

// 4-定义父组件里的方法
function borrowMoney() {
    money.value -= 100;
    return 100;
}

// 5-重点:暴露父组件的数据和方法
defineExpose({
    money,
    borrowMoney
});
</script>
  • 子组件:通过监听事件和$parent ,获取父组件向外暴露的响应式数据或者方法
<template>
    <div>
        <h1>我是子组件,我有 ${{ dau_money }}</h1>
        <!-- 1-重点:通过事件接收 $parent -->
        <button @click="borrow($parent)">向父组件借100块</button>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

// 定义子组件响应式数据
const dau_money = ref(0);

// 2-重点:通过$parent,拿到父组件暴露的数据与方法
function borrow($parent: any) {
	// $parent 里就有父组件暴露的 money属性 和 borrowMoney()方法
    // console.log($parent); 

    // 3-重点:调用父组件暴露的 borrowMoney()方法
    dau_money.value += $parent.borrowMoney();
    // 4-重点:可以查改父组件暴露的数据 money
    console.log('父组件还有 $' + $parent.money);
}
</script>