Another plugin

We could then import the state in component files when we need it, but it would be more convenient to be able to access it with a special getter called $state on the Vue prototype like we did for the fetch plugin. We will pass the state object to the plugin options, and the getter will return it.

  1. In the plugins folder, create a state.js file that exports the new plugin:
      export default {
install (Vue, state) {
Object.defineProperty(Vue.prototype, '$state', {
get: () => state,
})
}
}

Here we are using the JavaScript Object.defineProperty() method to set up a getter on the Vue prototype, so every component will inherit it!

One last thing--we need to install the state plugin!

  1. In the main.js file, import the new plugin:
      import VueState from './plugins/state'
  1. Then install it with the state object as the options parameter:
      Vue.use(VueState, state)

We can now use $state in our components to access the global state! Here is an example:

console.log(this.$state)

This should output the state object with the user property.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.151.141