vue3 语法糖 defineEmits defineExpose 父子组件方法调用

788 阅读1分钟

Vue3中,父组件可通过创建一个ref(null),将赋值的元素写在当前子组件上,通过定义的响应式变量,即可取得当前子组件内部dom以及变量方法等,并直接使用子组件内部方法。

vue3官方文档说明 Snipaste_2022-12-07_18-17-30.png

1. defineExpose

defineExpose可以主动把方法暴露出来

父组件

<template>
  <div>
    <child ref="child" />  // 通过ref
  </div>
</template>

<script setup>
const child = ref(null);  // ref
const handleClick = () => {
  child.value.restCurrentPage();  // 获取ref中的子组件方法
};
</script>

子组件

<script setup>
import { defineExpose } from 'vue';
const restCurrentPage = () => {
  console.log('要执行的操作');
};
defineExpose({ restCurrentPage });  // 将方法暴露出来
</script>

2. defineEmits

父组件

<template>
  <div>
    <child @getData="getData" />
  </div>
</template>

<script setup>
const getData = (e) => {
  console.log('getData', e); // 执行方法获取参数
};
</script>

子组件

<script setup>
import { defineEmits } from 'vue';
const data = ref('传值');
const emits = defineEmits([ 'getData' ]);

const emits = (e) => {
  defineEmits('getData', data.value);
};
</script>