B page returns to modify the value of the title of page A
//A页面
<template>
<text class="title">返回修改的值:{
{
title}}</text>
</template>
export default {
data() {
return {
title: 'Hello'
}
},
}
//B页面
<button @click="change">修改上一页的title值</button>
Solution 1: getCurrentPages()
Note: Although both are through getCurrentPages, the structure of the previous page printed by H5 and APP/small programs through getCurrentPages is different.
H5
change(e){
var pages = getCurrentPages();
var currPage = pages[pages.length - 1]; //当前页面
var prevPage = pages[pages.length - 2]; //上一个页面
//将前一页的title修改为"Hello World"
prevPage._data.title = 'Hello World'
//因为修改的是data里面的绑定数据,所以返回后页面数据会直接显示修改后的
uni.navigateBack()
},
APP/Mini Program
//B页面
change(e){
var pages = getCurrentPages();
var currPage = pages[pages.length - 1]; //当前页面
var prevPage = pages[pages.length - 2]; //上一个页面
//console.log(prevPage ); //按照打印结构这样赋值虽然成功但页面数据不会修改
// prevPage.data.$root[0].title = 'Hello World'
prevPage.setData({
title: 'Hello World'
})
uni.navigateBack()
},
//A页面,onShow方法,把setData的数据赋值到当前页面绑定的变量上
onShow(e) {
let pages = getCurrentPages();
let currPage = pages[pages.length-1];
if(currPage.data.title == undefined || currPage.data.title == ''){
}else{
this.title = currPage.data.title
}
},
Solution 2: $on monitoring
//A页面, onShow中添加监听一个handleFun的事件
onShow(){
uni.$on("handleFun", res => {
this.title = res.title;
// 清除监听
uni.$off('handleFun');
})
},
//B页面, 返回A页面触发一个事件,使用uni.$emit("handleFun",{
})
getAddress(){
uni.$emit("handleFun",{
title: 'Hello World'});
uni.navigateBack()
}
Reference: https://www.cnblogs.com/vicky123/p/12856011.html '