Method: You can rewrite the setItem method of localStorage. When the setItem method is called to set a new value, new
Event('setItemEvent') will be used to dispatch an event with the method of window.dispatchEvent() and let window listen
The following demo implements a page to obtain verses and then store the obtained data in localStorage and another page to monitor. Once the data changes, the console prints 'value changed' and prints out the new value.
Implementation steps:
1. First create a new utils folder under src, create a new tools.js, and write a dispatchEvent dispatch event such as: utils/tools.js
code show as below:
function 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)
}
}
export default dispatchEventStroage
2. Introduce tools globally in main.js and use them so that two vue components can trigger dispatch events
import tools from ‘./utils/tool.js’
Vue.use(tool)
3. Store data to localStorage in a vue component Here is to store the obtained verses
sendSentences.vue component
methods: {
getSentences() {
axios({
url: 'https://api.apiopen.top/api/sentences'
}).then(res => {
this.sentencesTitle = res.data.result.from
this.sentences = res.data.result.name
window.localStorage.setItem('gsStorename', JSON.stringify(this.sentences))
})
}
}
In another vue component, monitor localStorage data changes to assign values. The monitoring should be written in mounted (), where the 'value changed' will be printed, and the new value after each change will be printed. The code is as follows
watchSentences.vue pairs
mounted() {
// 监听localhostStorage的数据变化,结合utils/tool.js配合使用
window.addEventListener('setItemEvent', function(e) {
const newdata = JSON.parse(e.newValue)
console.log('值改变了',newdata)
})
}