vue3 defineEmits

简介:用于父子组件通信时,子组件向父组件传递数据,不需要被导入即可使用,会在编译 <script setup>语法块时一同编译。注意的是 defineEmits 只能在 <script setup>的顶层使用

使用
1、定义子组件

// 子组件 child.vue
 
<template>
  <button @click="handelClick">传递给父级</button>
  <button @click="add">加</button>
  <button @click="decrease">减</button>
</template>
 
<script setup lang="ts">

const emits = defineEmits(['clickFn', 'add', 'decrease'])// 定义一个或多个自定义事件

const handelClick = () => {
  emits('clickFn', { name: '张三', age: 18,id: 1 }) // 第一个参数为自定义事件名  第二个参数为要传递的数据
}
const add = () => {
  emits('add', 10) // 第一个参数为自定义事件名  第二个参数为要传递的数据
}
const decrease = () => {
  emits('decrease', 3) // 第一个参数为自定义事件名  第二个参数为要传递的数据
}

 
</script>

2、定义父组件

// 父组件 parent.vue
 
<template>
  <child @clickFn="updateInfo" />
  <button @click="handelClick">传递给父级</button>
  <button @click="handelAdd">加</button>
  <button @click="handelDecrease">减</button>
</template>
 
<script setup lang="ts">
import child from './child.vue'
import { ref } from 'vue'
const num = ref(10)

const updateInfo = (userInfo) => {
  console.log(userInfo) // { name: '张三', age: 18,id: 1 }
}
const handelAdd = (n) => {
  num.value += n
}
const handelDecrease = (n) => {
  num.value -= n
}
 
</script>

猜你喜欢

转载自blog.csdn.net/qq_37600506/article/details/132721098
今日推荐