uni.$emit(eventName,OBJECT)
触发全局的自定事件
uni.$on(eventName,callback)
监听全局的自定义事件。事件可以由 uni.$emit 触发,回调函数会接收所有传入事件触发函数的额外参数。
<template>
<view>
<button type="primary" @click="addNum">这是A组件</button>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
addNum() {
uni.$emit('updateNum', 10)
}
}
}
</script>
<style>
</style>
<template>
<view>这是B组件的数据{
{num}}</view>
</template>
<script>
export default {
data() {
return {
num:0
}
},
created() {
uni.$on('updateNum',num=>{
this.num += num
})
}
}
</script>
<style>
</style>
<template>
<view class="content">
<test :title="title" @myEvent="getNum"></test>
<test-a></test-a>
<test-b></test-b>
</view>
</template>
<script>
import test from '../../components/test.vue'
import testA from '../../components/a.vue'
import testB from '../../components/b.vue'
export default {
data() {
return {
title: '传给子组件'
}
},
methods: {
getNum(num) {
console.log(num)
}
},
components: {
test,
'test-a': testA,
'test-b': testB
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>