What is the best way to trigger a localstorage change event using Vue.js?

I'm currently facing an issue with my Vue app related to updating user information stored in localStorage. I've implemented a solution using websockets in App.vue within the mounted function, as shown below:

window.Echo.channel("user." + this.userData.id).listen(".user-updated", (user) => {
              localStorage.setItem('userData', JSON.stringify(user.user))
        });

While the real-time update of localStorage is working fine, the challenge lies in ensuring that all components display the updated information without requiring the user to refresh the page or switch routes.

Is there a method to simultaneously update all components from App.vue?

Answer №1

To trigger events, you have the option of utilizing an event bus or employing Vuex. Here is a demonstration:

window.Echo.channel("user." + this.userData.id).listen(".user-updated", (user) => {
              localStorage.setItem('userData', JSON.stringify(user.user));

              //trigger event
              EventBus.$emit('EVENT_USER_DATA_CHANGE', payLoad);
        });

Subsequently, in other components:

 mounted () {
    EventBus.$on(‘ EVENT_USER_DATA_CHANGE’, function (payLoad) {
      ...
    });
  }

Answer №2

To enable re-rendering, implement :key binding on the body or main container element. For example, you can use

<main :key="pageTrigger">
. Within your listening function, update the pageTrigger with new Date().getTime() to trigger a re-render of the components within the container.

If you are utilizing vuex as well, consider storing the pageTrigger in the store so that it can be accessed from any part of your application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm having trouble loading my Google Maps widget. Everything was functioning flawlessly until I attempted to hide it using the .hide function

After successfully implementing a Google Maps widget, I encountered an issue when trying to toggle its visibility using jQuery. Despite clicking on a div element to reveal the widget, the map fails to load inside the designated container. It seems as tho ...

Nuxt dynamically passes props through the router

Currently using Nuxt Experiencing difficulties with transferring data between pages Seeking to programmatically navigate to another page and pass a JavaScript object This is the code I have written so far: In my component where the navigation occurs: t ...

Learn how to automatically navigate to another page upon successfully creating an account and setting a value in the Firebase database

I am working on a system where, after successfully creating an account and setting a value in Firebase database, the user will be redirected to another page. Currently, I have managed to navigate to the next page but I am facing an issue with setting the ...

How can I incorporate a standalone Vuetify component into my Nuxt.js project?

Using Vuetify with nuxt.js specifically for the dashboard layout - how can I achieve this in my nuxt.config.js file? modules: [ //['nuxt-leaflet', { /* module options */}], 'bootstrap-vue/nuxt', '@nuxtjs/ax ...

Utilizing ES6 Functions to Transform Objects into Arrays

Is there a way to convert a JavaScript object into an array using ECMAScript-6? Take, for instance: var inputObj = {a:'foo', b:[1,2,3], c:null, z:55}; The desired outcome would look like this: ['foo', [1,2,3], null, 55] The seque ...

Establish a buffering system for the <video> element

Currently, I am facing an issue with playing videos from a remote server as they take an extended amount of time to start. It appears that the entire video must be downloaded before playback begins. Is there a way to configure the videos so they can begi ...

Exploring the world of JSON and JavaScript data structures

Can someone provide some clarification please? var a = '{"item":"earth", "color":"blue", "weight":920}'; Is the data type of a a string or an array ? var b = JSON.parse(a); What is the data type of b - an object or an array ? ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Create a custom style for Vue2-Google-Maps autocomplete feature that mirrors the sleek design of Vuetify

Is there a simple way to style the gmap-autocomplete field to resemble a vuetify v-text-field? I've tried using the Vuetify-google-autocomplete module, but it's causing more errors than expected. What is the most straightforward method to make & ...

How to add a new row to a Kendo grid with a unique custom styling

I am looking for a way to insert new data into a Kendo grid, but I want the added row to have a custom class so that I can style it with a different background color. How can I achieve this? I have searched through all the documentation but couldn't f ...

Tooltips will display on all Nivo charts except for the Nivo Line chart

I'm having an issue with nivo charts where the tooltip isn't showing up for my line chart. Even after copying and pasting the example from here: Other chart examples work fine with tooltips appearing, but for some reason, it's just not work ...

Utilizing AngularJS scope within a modal viewport

I am encountering an issue with my simple controller while fetching and displaying messages using $http.get in HTML using ng-repeat. The problem arises when trying to access the messages from a modal window, as it always prints the first message only. ind ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

Exploring techniques to compare two objects in JavaScript and then dynamically generate a new object with distinct values

var person1={ name:"Sarah", age:"35", jobTitle:"Manager" } var person2={ name:"Sarah Sanders", age:"35", jobTitle:"Manager" } //the name value has been updated in the above object, s ...

How can I incorporate images into my Vue Select dropdown?

Currently, I am using the vue-select component to display dropdowns on my website. These dropdowns are populated with data provided through the :options attribute. Specifically, I am working on implementing a credit card dropdown and would like to includ ...

What is the significance of using the "why" in the href property within the

I need help understanding why the plus "+" is used before and after myUrl in the function .not. Even though it works fine with or without the +, I am curious about why it was included in the code snippet. <script type="text/javascript"> $(documen ...

What is the best method for installing Raphael.js using bower?

Currently, I am attempting to incorporate Raphael.js into my project in a highly modular manner. Since Raphael has a registered bower component, utilizing that option seemed like the most logical choice. Following some instructions from the Snap.svg readm ...

Decoding the enigma of addEventListener in Nuxt: Unveiling the "referenceError: window is not defined" issue

I am currently working on developing a hamburger menu, but I have encountered an error. The error message states: ReferenceError: window is not defined. The issue seems to be within the created section of the code. <script> export default { ...

Is there a way to iterate through objects and add new properties to them?

I am trying to achieve the following object: let newPost = { title: "Post 1", Content: "New content" } with the code below: let newPost = {}; let postData = $(".post-data").each (function(index) { newPost.title = $ ...

The onChange event was not able to be activated within the material-ui radioGroup component

Utilizing the RadioButton component to showcase different options of a question within a custom-built component: import FormControl from "@material-ui/core/FormControl"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Grid from " ...