vue.js - 如何检测用户返回页面而不是开始浏览?
问题描述
我有一个网格组件,我在我的应用程序的许多路线中使用它。我想保持它的状态(即分页,搜索参数)并在用户返回网格时恢复它(即从编辑一行)。另一方面,当用户启动新流程(即通过单击链接)时,页面将设置为零,并使用默认参数调用 Web 服务。
我如何识别用户确实回来而不是开始新流程?
当我研究这个问题时,我遇到了以下解决方案。不幸的是他们没有为我服务
1/ 使用路由器滚动行为
scrollBehavior(to, from, savedPosition) {
to.meta.comeBack = savedPosition !== null;
}
它确实告诉我用户是否回来。不幸的是,滚动行为在网格的创建和挂载钩子被调用之后运行。这样我就没有地方放我的代码来恢复状态了。
2/ 使用 url 参数
网格的路线将有一个可选参数。当参数为空时,代码会知道这是一个新流程并使用 $router.replace 例程设置一个新流程。然后用户会去编辑,回来,代码会知道他们回来了,因为路由参数!= null。问题是调用 $router.replace 会重新创建组件(即调用钩子等)。此外,可选参数会混淆 vue-router 与路由中的其他可选参数。
解决方案
历史部分
// component ...
// can error and only serves the purpose of an idea
data() {
return {
history: []
}
},
watch: {
fullRoute: function(){
this.history.push(this.fullRoute);
this.$emit('visited', this.visited);
}
},
computed: {
fullRoute: function(){
return this.$route.fullPath
},
visited: function() {
return this.history.slice(-1).includes(this.fullRoute)
}
}
数据方式
// component ...
// can error and only serves the purpose of an idea
computed: {
gridData: {
get: function() {
return JSON.parse(local.storage.gridData)
},
set: function(dataObj){
local.storage.gridData = JSON.stringify(dataObj)
}
}
}
//...
// component ...
// can error and only serves the purpose of an idea
computed: {
gridData: {
get: function() {
return this.$store.state.gridData || {}
},
set: function(dataObj){
this.$store.dispatch("saveGrid", gridData)
}
}
}
//...
// component ...
// can error and only serves the purpose of an idea
computed: {
gridData: {
get: function() {
return window.gridData || {}
},
set: function(dataObj){
window.gridData = dataObj
}
}
}
推荐阅读
- reactjs - 将 non-create-react-app React 项目部署到 Github Pages 时出现问题
- python - 搜索中的 Visual Studio Code 键绑定
- javascript - 我如何从输入值文本中获取?
- web2py - 我可以使用虚拟字段在 web2py 中显示链接表的值吗?
- json - 将属性添加到反序列化 Json 类
- function - 闭包函数 - 返回全局变量?
- apache-kafka - 为什么卡夫卡不适合我?
- excel - 使用下拉列表过滤 Excel 表格
- python - 在 Python 中将分类值列转换为其统计值
- javascript - 在 PhantomJS/Sinon 中存根 Promise