event-bus.uvue 1.5 KB
Newer Older
Q
qiang 已提交
1
<template>
DCloud-WZF's avatar
DCloud-WZF 已提交
2
  <!-- #ifdef APP -->
H
hdx 已提交
3 4
  <scroll-view class="page-scroll-view">
  <!-- #endif -->
DCloud-WZF's avatar
DCloud-WZF 已提交
5 6 7
    <view>
      <button @click="on">开始监听</button>
      <button @click="once">监听一次</button>
8 9
      <button @click="off">取消监听</button>
      <button @click="offAll">取消全部监听</button>
DCloud-WZF's avatar
DCloud-WZF 已提交
10 11 12 13 14 15 16
      <button @click="emit">触发监听</button>
      <button @click="clear">清空消息</button>
      <view class="box">
        <view>收到的消息:</view>
        <view>
          <view v-for="(item, index) in log" :key="index">{{ item }}</view>
        </view>
Q
qiang 已提交
17 18
      </view>
    </view>
H
hdx 已提交
19
  <!-- #ifdef APP -->
DCloud-WZF's avatar
DCloud-WZF 已提交
20 21
  </scroll-view>
  <!-- #endif -->
Q
qiang 已提交
22 23
</template>

H
hdx 已提交
24 25 26 27 28 29
<script>
  export default {
    data() {
      return {
        log: [] as string[],
      }
Q
qiang 已提交
30
    },
H
hdx 已提交
31 32 33
    methods: {
      fn(res : string) {
        this.log.push(res)
34 35 36
      },
      fn2(res : string) {
        this.log.push(res)
H
hdx 已提交
37 38 39
      },
      on() {
        uni.$on('test', this.fn)
40 41 42
      },
      on2() {
        uni.$on('test', this.fn2)
H
hdx 已提交
43 44 45 46 47 48
      },
      once() {
        uni.$once('test', this.fn)
      },
      off() {
        uni.$off('test', this.fn)
49 50 51 52
      },
      offAll() {
        // TODO 第二个参数为可选,后续优化后可不传递
        uni.$off('test', null)
H
hdx 已提交
53 54 55 56 57 58 59
      },
      emit() {
        uni.$emit('test', 'msg:' + Date.now())
      },
      clear() {
        this.log.length = 0
      },
DCloud-WZF's avatar
DCloud-WZF 已提交
60
    },
H
hdx 已提交
61
  }
Q
qiang 已提交
62 63 64
</script>

<style>
H
hdx 已提交
65 66 67 68
  .box {
    padding: 10px;
  }
</style>