Vue3 基于setup语法糖(script setup)的父组件调用子组件中的方法🍬
⭕️ 知识点:vue3;setup语法糖;组件ref;
⭕️ 以下例子实现了在父组件中,点击按钮,调用子组件中的changeNum()方法
父组件:
<template>
<Son1 ref="son1" />
<button @click="changeNum">点击调用子组件中的方法</button>
</template>
<script setup>
import Son1 from "./components/Son1.vue";
import { ref } from "vue";
// 关键代码
let son1 = ref();
function changeNum(){
son1.value.changeNum()
}
</script>
子组件:
<template>
<div>Son1: {{num}}</div>
</template>
<script setup>
import {ref,defineExpose} from 'vue'
let num = ref(10);
// eslint-disable-next-line no-unused-vars
function changeNum(){
num.value = 100
}
// 记得暴露
defineExpose({
changeNum
});
</script>