吾心信其可行,则移山填海之难,终有成功之日。——孙中山
vue
官方文档——程序化的事件侦听器
vue
官方文档——实例方法/事件
我们可以使用this.$on
在vue
中侦听一个事件
1 2 3
| vm.$on('test', function (msg) { console.log(msg) })
|
然后我们可以在其他地方访问它
例如这里,我在一个页面中使用vm.$on

而在另一处中使用vm.$emit

可以看到成功调用test
事件
基于这一点,我们可以在uniapp
中进行页面间的通信
uniapp
官方文档
也就是说,在其中一个页面中我们使用uni.$on
或者uni.$once
,在另一个页面中就可以使用uni.$emit
进行调用,前提是uni,$on
或者uni.$once
必须触发成功
uni.$once
触发后就会立马移除该监听器,也就是说只能触发一次
而uni.$on
就只能使用uni.$off
进行手动移除
比如我这里在index.nvue
页面中挂载

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <template> <view> <view>{{ val }}</view> </view> </template>
<script> export default { data() { return { val: 0 }; }, onLoad() { uni.$on('add', this.add); }, methods: { add(e) { console.log('主页的add被触发了!: ', e); this.val += e.data; } } }; </script>
|
然后到list
页面中调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <view> </view> </template>
<script> export default { data() { return { }; }, onLoad() { setInterval(() => { uni.$emit('add', { data: 2 }); }, 1000); }, methods: { } }; </script>
|
我们进入index
页面,再进入list
页面触发后,回到index
页面就可以看到它的add
函数成功触发了每秒加2的效果