在移动端component要切来切去的,下面这样写感觉很乱,
想知道有没有更优雅的处理方式?
detailShow = false;
contactShow = false;
searchShow = false;
homeShow = true;
goBackHome() {
this.detailShow = false;
this.contactShow = false;
this.searchShow = false;
this.homeShow = true;
}
goContact() {
this.homeShow = false;
this.detailShow = false;
this.searchShow = false;
this.contact = true;
}
goSearch() {
this.homeShow = false;
this.detailShow = false;
this.contactShow = false;
this.searchShow = true;
}
###用一个字符串变量 showPage 控制显示
this.showPage === 'home' 时显示home页面
this.showPage === 'detail' 时显示detail页面
以此类推
跳转方法也是写一个就好了
show(page) {
this.showPage = page;
}
###
建议使用常量控制状态,
例子:
`
const enum PAGE_STAT {
LOADING,
UPDATE,
ADD,
DELETE
}
或者
const enum PAGE_STATE {
HOME_PAGE: 'HOME',
DETAIL_PAGE: 'DETAIL_PAGE',
...
}
`
主要是防止魔法数字,或者魔法字符串(有值无意),比如用 新增 :1 , 编辑:2,删除:3
`
if(type === 1 ) { // 新增
}
修改
const enum STATE{
ADD: 1,
UPDATE : 2
}
if(type === STATE.ADD) { //新增
}
`
推荐使用 hooks 库:https://hooks.umijs.org/
~~
如果你是想统一这几个函数,可以使用下面的函数
goPage(page) {
const arr = ['detail', 'contact', 'search', 'home'];
arr.forEach(item => {
this[`${item}Show`] = page.toLowerCase() === 'item'
});
}
如果你是想有优化这几个状态值,由于具体的业务逻辑我不清楚,所以没什么太好的建议