$on、注册事件
$once注册单次事件
$emit、触发事件
$off、注销事件
o
n
、
on、
on、emit、$off常用于跨页面、跨组件通讯,这里为了方便演示放在同一个页面
<template>
<view class="content">
<view class="data">
<text>{{val}}</text>
</view>
<button type="primary" @click="comunicationOff">结束监听</button>
</view>
</template>
<script>
export default {
data() {
return {
val: 0
}
},
onLoad() {
setInterval(()=>{
uni.$emit('add', {
data: 2
})
},1000)
uni.$on('add', this.add)
},
methods: {
comunicationOff() {
uni.$off('add', this.add)
},
add(e) {
this.val += e.data
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.data {
text-align: center;
line-height: 40px;
margin-top: 40px;
}
button {
width: 200px;
margin: 20px 0;
}
</style>
注意事项
uni.
e
m
i
t
、
u
n
i
.
emit、 uni.
emit、uni.on 、 uni.
o
n
c
e
、
u
n
i
.
once 、uni.
once、uni.off 触发的事件都是 App 全局级别的,跨任意组件,页面,nvue,vue 等
使用时,注意及时销毁事件监听,比如,页面 onLoad 里边 uni.
o
n
注
册
监
听
,
o
n
U
n
l
o
a
d
里
边
u
n
i
.
on 注册监听,onUnload 里边 uni.
on注册监听,onUnload里边uni.off 移除,或者一次性的事件,直接使用 uni.$once 监听