Saturday, February 24, 2018

Is there any way to store the emitted data once the emitted data is fetched?

Leave a Comment

I am using EventBus. My code is below.

app.js

window.EventBus = new Vue(); 

Below is the code that Emit

EventBus.$emit('emitted', {     SomeProperty: SomeData, }); 

Below is the code to retrieve the emitted data

EventBus.$on('emitted', id => {  }); 

Is there any way to store the emitted data once the emitted data is fetched? I am trying to search if there is any way to save the emitted data somewhere?

3 Answers

Answers 1

To save data and share between components, use vuex

To save data in localstorage, for convenience you can use vue-ls

Answers 2

So far, I found below approach.

To get saved data.

localStorage.getItem("Key") 

To save data

localStorage.setItem("Key") 

Answers 3

Since you're using Vue with Laravel:

    // Your event bus     const EventBus = new Vue()      // The main Vue instance for your app     const app = new Vue({         // ALL YOUR APP LOGIC GOES HERE...        methods: {         fetchData (params) {           // this is the method you use to fetch data, here you can use a library           // like axios to query your api and return the result                 return axios.get('/api/someData', { params })         }       },       // Every time your app is loaded, execute created() hook to retrieve       // previously stored data from localStorage       // depending on your needs, you can use mounted() hook instead.       created () {         // Attach the listener to store someData in localStorage         EventBus.$on('someData', data => window.localStorage.setItem('someData', data))          // check for stored someData         const someData = window.localStorage.getItem('someData')          if (someData) {             // do something with someData         }         else {             // there is no someData stored, so fetch and store ($emit)             this.fetchData()             .then(response => {               if (response.data.someData) {                 EventBus.$emit('someData', response.data.someData)               }             })         }       }     }) 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment