Vue自定义事件

141 阅读1分钟

什么是自定义事件

在封装组件时,为了让组件的使用者可以监听到组件内状态的变化,此时需要到组件的自定义事件

Screenshot_2023_0403_224145.png

自定义属性的3个步骤

在封装组件时:
1.声明自定义事件
2.触发自定义事件
在使用组件时:
3.监听自定义事件

声明自定义事件

开发者为自定义组件封装的自定义事件,必须事先在emits节点中声明:

<template>
  <h3>Counter组件</h3>
  <button>+1</button>
</template>

<script>
export default{
//my-counter 组件的自定义事件,必须事先声明到emits节点中
emits:['change']
}
</script>
触发自定义事件

在emits节点下声明的自定义事件,可以通过this.$emits(),触发自定义的change事件:

<template>
  <h3>Counter组件</h3>
  <button @click="onBtnClick">+1</button>
</template>

<script>
export default{
//my-counter 组件的自定义事件,必须事先声明到emits节点中
emits:['change'],
methods:{
  onBtnClick(){
  this.$emits('change')
  }
}
</script>

在使用自定义组件时,可以通过v-on的形式监听自定义事件

<my-counter @change="getCount"><my-counter/>

methods:{
getCount(){
console.log('监听到了count值的变化')
  }
}

在emits节点声明的自定义事件,可以通过this.$emits(自定义事件的名称)方法进行触发

<template>
  <h3>Counter组件</h3>
  <button>+1</button>
</template>

<script>
export default{
//my-counter 组件的自定义事件,必须事先声明到emits节点中
emits:['change'],
methods:{
  onBtnClick(){
  this.$emits('change')
  }
}
</script>