this.$emit 和uni.emit
时间: 2023-11-08 07:03:27 浏览: 51
this.$emit和uni.emit都是用于Vue.js中进行自定义事件触发的方法,它们的作用都是触发当前组件实例上的指定事件。
this.$emit是Vue.js中的原生方法,用于向父组件触发自定义事件,可以携带参数。使用方式为在当前组件实例内部使用this.$emit(eventName, [...args])来触发事件。
uni.emit是在Uni-app中自定义的方法,用于向非父子关系的组件或页面传递事件,可以携带参数。使用方式为在当前页面或组件实例内部使用uni.emit(eventName, [...args])来触发事件。
相关问题
this.$emit和uni.$emit
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>
```
uni.$emit和$emit的区别
uni.$emit和this.$emit的作用是相同的,都是用于触发自定义事件。它们的区别在于使用场景不同。uni.$emit是在非Vue组件中使用的,而this.$emit是在Vue组件中使用的。在Vue组件中,可以使用this.$emit来触发自定义事件,并且可以在父组件中使用v-on来监听这个事件。而在非Vue组件中,可以使用uni.$emit来触发自定义事件,并且可以在其他非Vue组件中使用uni.$on来监听这个事件。
举个例子,假设我们有两个页面A和B,现在需要在A页面中触发一个自定义事件,并将数据传递给B页面。可以在A页面中使用uni.$emit来触发这个事件,并在B页面中使用uni.$on来监听这个事件并获取数据。
以下是一个示例代码:
在A页面中触发自定义事件并传递数据:
```javascript
uni.$emit('add', {listData: [1, 2, 3]});
```
在B页面中监听自定义事件并获取数据:
```javascript
uni.$on('add', function(res) {
console.log(res.listData); // 输出:[1, 2, 3]
});
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)