vue3-defineEmits与defineExpose

1,179 阅读1分钟

vue3-defineEmits与defineExpose方法

这两个api的基础使用方式

父组件

<template>
  <ButtonNewVue ref="btn" :title="title" @btn-self="doSomething" />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import ButtonNewVue from './components/ButtonNew.vue'

const title = ref('新的标题')

const btn = ref()

// 自定义事件的事件处理函数
const doSomething = (arg: string) => {
  title.value = title.value + arg
  console.log(btn.value.count) // 子组件暴露的属性
  btn.value.func() // 子组件暴露的方法
}
</script>

<style scoped></style>

子组件

<template>
  <h2>{{ title }}</h2>
  <button @click="onChangeTitle">{{ content }}</button>
  <div>{{ count }}</div>
</template>

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

// defineProps 接收父组件传过来的属性
withDefaults(defineProps<{ title: string; content: string }>(), {
  title: '标题',
  content: 'button'
})

// defineEmits 接收父组件传过来的方法
// 第一种:
// e:'自定义事件名称'
// const emit = defineEmits<{ (e: 'btn-self', arg: string): void }>()

// 第二种:个人的话,这种方式用的比较多
// 数组中的元素,就是自定义事件的名称
const emit = defineEmits(['btn-self'])

const onChangeTitle = () => {
  emit('btn-self', '123') // 第一个参数是自定义事件,第二个参数是传的值
}

const count = ref(121212)
const func = () => {
  console.log('今天是个好日子')
}

// defineExpose 使得子组件可以暴露一些自身的属性或者方法,让父组件通过ref模板引用拿到
defineExpose({
  count,
  func
})
</script>