[TOC]

vue3中常用语法

1. 子组件调用父组件方法

1.1 子组件使用$emit

父组件:

<template>
  <ChildComponent @call-parent-method="parentMethod" />
</template>
 
<script setup>
import { defineComponent } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const parentMethod = () => {
  console.log('This is a parent method');
};
</script>

子组件:

<template>
  <button @click="$emit('call-parent-method')">Call Parent Method</button>
</template>
<script setup>
import { defineComponent, defineEmits } from 'vue';
 
const emit = defineEmits(['call-parent-method']);
const handleOk = () => {
  emit('call-parent-method'); // 在JS里面调用
}
</script>
Last Updated: 1/10/2025, 5:15:39 PM