Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to monitor local storage in real time in vue

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to monitor local storage in real time in vue". In daily operation, I believe that many people have doubts about how to monitor local storage in real time in vue. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to monitor local storage in real time in vue". Next, please follow the editor to study!

How to monitor local storage in real time

In main.js

Vue.prototype.$addStorageEvent = function (type, key, data) {if (type = 1) {/ / create a StorageEvent event var newStorageEvent = document.createEvent ('StorageEvent'); const storage = {setItem: function (k, val) {localStorage.setItem (k, val); / / initialize the created event newStorageEvent.initStorageEvent (' setItem', false, false, k, null, val, null, null) / / dispatch object window.dispatchEvent (newStorageEvent);}} return storage.setItem (key, data);} else {/ / create a StorageEvent event var newStorageEvent = document.createEvent ('StorageEvent'); const storage = {setItem: function (k, val) {sessionStorage.setItem (k, val) / / initialize the created event newStorageEvent.initStorageEvent ('setItem', false, false, k, null, val, null, null); / / dispatch object window.dispatchEvent (newStorageEvent);}} return storage.setItem (key, data);}}

Trigger when you want it

This.$addStorageEvent (2, "butCountNum", this.butCount)

Listening in the mouted hook function

Window.addEventListener ('setItem', (e) = > {if (e.key = "butCountNum") {/ / write logic} vue listens for data changes

Listening for data changes is achieved through listeners in Vue, and you can also think of it as a listener that listens for changes in data all the time.

The basic usage of watch

Earlier, we added data and methods to js, but this time we are going to add the watch attribute. Let's take a look at the location where listeners are added:

Export default {name: "app", / / data data () {return {};}, / / method methods: {}, / / listener watch: {}}

A simple example:

The number of times you click the button is: {{count}}

Click export default {name: "app", data () {return {count:0}}, methods: {add () {this.count++;}}, watch: {/ / the variable count count () {console.log ('count has changed');}

Listeners are more often used in asynchronous operations, which are operations in which data returns are delayed. For example, if we request a backend interface, the interface will return data to us, and then we will render the data on the page.

It takes a certain amount of time from the request interface to the return data, so we can use the listener to listen for the returned data, and when the data is returned, we trigger the rendering.

Simulate a pseudo-asynchronous operation:

Data obtained from the input box: {{passedInputValue}}

Export default {name: "app", data () {return {inputValue:', passedInputValue:'}}, watch: {inputValue () {/ / when inputValue data is changed, delay assignment to passedInputValue setTimeout (() = > {this.passedInputValue = this.inputValue) }, 3000)}

At this point, you will find that when you type the text in the input input box, the data in the p tag does not change immediately, but will not be rendered until three seconds later.

Get the previous value

In some scenarios, we need the last data, and at this point, the listener can give us two values, the old value and the new value.

Based on the previous case, we only need to add one parameter to get the old value. The code is as follows:

Watch: {inputValue (value,oldValue) {/ / the first parameter is the new value, the second parameter is the old value, and the order console.log (`new value: ${value} `) cannot be changed; console.log (`old value: ${oldValue}`);}} handler method and immediate attribute

We already know that the listener will not be triggered when the value we are listening to has not changed, and the listener will not be triggered the first time the page is rendered.

But now I have a need to trigger the listener when the page is rendered for the first time.

A method and a property are used at this point.

FullName: {{fullName}}

FirstName:

Export default {name: "app", data () {return {firstName: 'Su', lastName:' Junyang', fullName:'}}, watch: {firstName: {handler (newName, oldName) {this.fullName = newName +''+ this.lastName }, / / if false is set, the listener immediate: true}} will not be triggered after the first rendering of the page; deep deep listening

The so-called deep listening is the value of the internal properties of the listening object.

The listeners we used before can only listen for changes in one variable, (focus on the comments in the code) for example:

Data: {return {/ / string changes, you can listen to firstName: 'Su', room: {name: "big bed room", / / when the room number changes, the listener cannot hear it. / / because the listener only listens to room, not number or name number: 302}

At this point, we need to listen deeply.

Deep snooping is not difficult to implement in code. You just need to add a deep attribute to handler, as shown in the following code:

Watch: {room: {handler (newRoom,oldRoom) {console.log ("room number has changed")}, deep: true}}

Case: pseudo-fuzzy search using listeners and timers

{{element}} export default {name: 'app', data () {return {results: [], mockData: [' Zhejiang University', 'Renmin University of China', 'Tsinghua University', 'Middle School affiliated to Tsinghua University', 'Zhejiang University of Technology', 'Zhejiang University of Technology'] InputValue:''} }, watch: {inputValue (value) {if (!! value) {setTimeout () = > {this.results = this.mockData.filter (el = > {console.log (value); return el.indexOf (value)! = =-1;});}, 300);} At this point, the study on "how to monitor local storage in real time in vue" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report