event-bus.uvue 1.9 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
      <button @click="off">取消监听</button>
9
      <!-- <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>
17 18 19 20 21 22
      <button @click="onObj">开始监听 obj 参数</button>
      <button @click="emitWithObj">触发监听 obj 参数</button>
      <view class="box">
        <text>接收到的 obj 参数:</text>
        <text>{{JSON.stringify(objArg)}}</text>
      </view>
Q
qiang 已提交
23 24
      </view>
    </view>
H
hdx 已提交
25
  <!-- #ifdef APP -->
DCloud-WZF's avatar
DCloud-WZF 已提交
26 27
  </scroll-view>
  <!-- #endif -->
Q
qiang 已提交
28 29
</template>

H
hdx 已提交
30 31 32 33 34
<script>
  export default {
    data() {
      return {
        log: [] as string[],
35
        objArg: {},
H
hdx 已提交
36
      }
Q
qiang 已提交
37
    },
H
hdx 已提交
38 39 40
    methods: {
      fn(res : string) {
        this.log.push(res)
41 42 43
      },
      fn2(res : string) {
        this.log.push(res)
H
hdx 已提交
44 45 46
      },
      on() {
        uni.$on('test', this.fn)
47 48 49 50 51 52 53 54
      },
      on2() {
        uni.$on('test', this.fn2)
      },
      onObj() {
        uni.$on('test-obj', (res: UTSJSONObject) => {
          this.objArg = res
        })
H
hdx 已提交
55 56 57 58 59 60
      },
      once() {
        uni.$once('test', this.fn)
      },
      off() {
        uni.$off('test', this.fn)
61 62 63
      },
      offAll() {
        uni.$off('test')
H
hdx 已提交
64 65 66 67
      },
      emit() {
        uni.$emit('test', 'msg:' + Date.now())
      },
68 69 70
      emitWithObj() {
        uni.$emit('test-obj', { a: 1, b: 2 })
      },
H
hdx 已提交
71 72 73
      clear() {
        this.log.length = 0
      },
DCloud-WZF's avatar
DCloud-WZF 已提交
74
    },
H
hdx 已提交
75
  }
Q
qiang 已提交
76 77 78
</script>

<style>
H
hdx 已提交
79 80 81
  .box {
    padding: 10px;
  }
82
</style>