this.$emit和uni.$emit
时间: 2023-12-16 07:28:28 浏览: 61
this.$emit和uni.$emit都是用于在Vue组件中触发自定义事件的方法。它们的用法类似,都需要传递两个参数:事件名称和要传递的数据。具体区别在于this.$emit是Vue实例的方法,而uni.$emit是uni-app框架的方法。
下面是一个使用this.$emit触发自定义事件的例子:
```javascript
// 子组件中触发自定义事件
this.$emit('my-event', 'hello world')
// 父组件中监听自定义事件
<template>
<child-component @my-event="handleEvent"></child-component>
</template>
<script>
export default {
methods: {
handleEvent(data) {
console.log(data) // 输出:hello world
}
}
}
</script>
```
下面是一个使用uni.$emit触发自定义事件的例子:
```javascript
// 子组件中触发自定义事件
uni.$emit('my-event', 'hello world')
// 父组件中监听自定义事件
<template>
<child-component></child-component>
</template>
<script>
export default {
mounted() {
uni.$on('my-event', data => {
console.log(data) // 输出:hello world
})
}
}
</script>
```