小程序案例说明
一般新增后或者编辑后,刷新上个页面数据
one
setTimeout(() => {
this.$common.prePage().list = []
this.$common.prePage().getList()
this.$common.back(1)
}, 1200);
prePage()方法封装:
const prePage = () => {
let pages = getCurrentPages();
let prePage = pages[pages.length - 2];
// #ifdef H5
return prePage;
// #endif
return prePage.$vm;
}
two
let pages = getCurrentPages();
let prePage = pages[pages.length - 3];//上上个页面
prePage.getInfo()
二、页面通讯
通过uni页面生命周期函数和事件通知机制,实现在新增数据后刷新上一个页面的列表。
假设您是从list页面跳转到add页面进行数据新增,下面是一个示例代码:
在add页面js文件中,使用uni.$emit触发refreshList事件,将新增的数据传递给list页面:
// add.vue
// 假设成功新增数据后返回了一个obj对象,包含新增数据的信息
this.$http.post('/api/addData', formData).then((res) => {
let obj = res.data
// 触发事件refreshList,将obj作为参数传递给list页面
uni.$emit('refreshList')
}).catch((err) =>{
console.log(err)
})
在list页面mounted函数中,使用uni.$on监听refreshList事件,接收新增数据,并调用相应的获取数据列表的方法重新渲染列表:
// list.vue
mounted() {
// 监听refreshList事件
uni.$on('refreshList', () =>{
// 调用获取数据列表的方法重新渲染列表
this.getDataList()
})
},
methods: {
getDataList(){
// 执行获取数据列表的逻辑
// ...
}
}
H5里面【经过测试,有bug】,电脑一切正常,但是打包之后手机不可以。
如果prePage.$vm里面一直没有暴露出去的数据,可以试试
const masterTxt = ref('') //所属师傅名称
const sale_after_id = ref('') //师傅id
defineExpose({
masterTxt,
sale_after_id,
}) //把数据暴露出去
i.prePage().$.setupState.masterTxt = (list.value ? masterTxt.value : 0) //修改上一页面的值
i.prePage().$.setupState.sale_after_id = (list.value ? sale_after_id.value : 0) //修改上一页面的值
i.back()
let pages = getCurrentPages(); // 当前页面
if (pages.length >= 2) {
let prevPage = pages[pages.length - 2]; // 上一页
prevPage.$.setupState.sale_after_id = (list.value ? sale_after_id.value : 0) //修改上一页面的值
i.back()
}
.$.setupState
页面通讯
uni.$emit()
和uni.$on()
和uni.$off('')
在下单页面,点击选择人员按钮跳转到人员管理,在人员管理页面选择好人员后,使用uni.$emit()
传参 、在下单页面使用uni.$on()
监听,最后使用uni.$off('')
清除
代码
下单页:
import {
onLoad,
onUnload
} from '@dcloudio/uni-app'
const masterTxt = ref('') //所属师傅名称
const sale_after_id = ref('') //师傅id
onLoad((options) => {
uni.$on('masterSucc', (e) => {
masterTxt.value = e.masterTxt
sale_after_id.value = e.sale_after_id
})
})
onUnload(() => {
uni.$off('masterSucc')
})
人员管理页面:
uni.$emit('masterSucc', {
masterTxt: masterTxt.value, //人员名称
sale_after_id: sale_after_id.value //人员id
})