自 HBuilderX 2.0.0 起支持 uni.$emit
、 uni.$on
、 uni.$once
、uni.$off
,可以方便的进行页面的通讯 ,触发的事件都是 App 全局级别的,跨任意组件,页面,nvue,vue 等
uni.$emit('firstHandle1', { name: 'my name is first1' + this.name });
onLoad() {
uni.$on('firstHandle1', item => {
console.log(item, '第一页面数据');
});
uni.$on('secondHandle', item => {
console.log(item, '第二个页面的数据');
});
}
onUnload() {
uni.$off('firstHandle1');
uni.$off('secondHandle');
}
得到结果是:index/index页面
跳转到first/index页面
;再从first/index
页面返回就会打印{name: "my name is first10"} "第一页面数据"
从second/index
返回first/index页面
则会打印:{name: "my name is second"} "第二页面数据"
其他数据不会打印
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area"><view class="title" @click="hello()">go first</view></view>
</view>
</template>
<script>
// const api = require('../../utils/api.js');
export default {
data() {
return {};
},
onLoad() {
uni.$on('firstHandle1', item => {
console.log(item, '第一页面数据');
});
uni.$on('secondHandle', item => {
console.log(item, '第二个页面的数据');
});
},
methods: {
hello() {
uni.$emit('homeHandle', { name: '我是首页' });
uni.navigateTo({
url: '../first/index'
});
}
},
onUnload() {
uni.$off('firstHandle1');
uni.$off('secondHandle');
}
};
</script>
<template>
<view>
<view @click="goBack()">返回</view>
<view @click="goSecond()">跳转到第二页面</view>
</view>
</template>
<script>
export default {
data() {
return {
name: 0
};
},
onLoad() {
uni.$on('secondHandle', item => {
console.log(item, '第二页面数据');
});
uni.$on('homeHandle', item => {
console.log(item, '首页的数据');
});
},
methods: {
goBack() {
uni.$emit('firstHandle1', { name: 'my name is first1' + this.name });
uni.navigateBack({});
},
goSecond() {
uni.$emit('firstHandle2', { name: 'my name is first2' });
uni.navigateTo({
url: '../second/index'
});
}
},
onUnload() {
uni.$off('secondHandle');
uni.$off('homeHandle');
}
};
</script>
<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() {
uni.$on('firstHandle2', item => {
console.log(item, '第一页面的数据呀');
});
},
methods: {
comunicationOff() {
uni.$emit('secondHandle', { name: 'my name is second' });
uni.navigateBack({ delta: 1 });
}
},
onUnload() {
uni.$off('firstHandle2');
}
};
</script>