vue 项目,uniapp项目通过监听缓存里面值发生改变来进行想过逻辑处理的实用方法
`/**
* 重写setItem事件,当使用setItem的时候,触发,window.dispatchEvent派发事件 使用方法
* let _this = this
* // 根据自己需要来监听对应的key
* window.addEventListener('setItemEvent', function (e) {
* // e.key : 是值发生变化的key
* // e.newValue : 是可以对应的新值
* if (e.key === 'goChangeimage') {
* console.log(e.newValue)
* if (e.newValue) {
* localStorage.removeItem('goChangeimage')
* }
* }
* })
*/
dispatchEventStroage() {
const signSetItem = localStorage.setItem
localStorage.setItem = function(key, val) {
let setEvent = new Event('setItemEvent')
setEvent.key = key
setEvent.newValue = val
window.dispatchEvent(setEvent)
signSetItem.apply(this, arguments)
}
},
`# 通过在项目中的工具文件夹下。 创建一个js文件。 定一个dispatchEventStroage方法,方法内部调用window的window.dispatchEvent派发事件。
这单独的页面中使用 可以在created()函数中创建一个监听器用来监听你所需要监听的storage值的改变,来进行相关的逻辑处理
监听路由的方法
let _this = this
// 根据自己需要来监听对应的key
window.addEventListener('setItemEvent', function (e) {
// e.key : 是值发生变化的key
// e.newValue : 是可以对应的新值
if (e.key === 'token') {
console.log(e.newValue)
if (e.newValue) {
//对应的逻辑处理
localStorage.removeItem('token')
}
}
})
vue项目中。uniapp 中。监听路由的方法:
watch:{
'$route' (to, from) {
if (this.$route.query.name) {
//进行自己的逻辑处理
} else {
}
}
}
对路由地址进行截取 去对应的参数
如果$route.query 中取不到对应的参数值。可以使用这个方法来获取参数
let arr = this.$route.fullPath.split('?')[1].split('=')
let arr1 = arr[1].split('&')