[Vuejs]-Sharing Data Between Components without child/parent – Vue

0👍

there are many ways to share data from different components:

  1. uex

vuex is the best way to manage your apps state,but is much more heavy for small project

  1. customevent

customevent is easier than vuex to cast data in your app

var event = new CustomEvent('customE', {
        "detail": {
          //your data here
        }
      })
window.dispatchEvent(event)
//get data
window.addEventListener("customE", (e)=>{
//get your data here
e.detail
});
  1. storage

you can use localstorage or sessionstorage to cast your data and use storage event to get your data,you will dispatch storage event as you change customData value:

localStorage.customData = JSON.stringify('your Json data')
window.addEventListener('storage', (e) => {
//make sure you filter your data key
  if (e.key === 'customData') {
    //get your data here
    e.newValue
  }
}
)

Leave a comment