How does the store work and what is so special about it?

The Vuex store contains essentially two things: state and mutations. State is an object that represents the initial state of the application data. Mutations is also an object containing action functions that affect the state. Vuex store is just a plain JavaScript file that exports these two objects and tells Vue to use Vuex (Vue.use(Vuex)). Then it can be imported into any other component. If you import it in the main App.vue file and register the store on the Vue application initialization, it is passed to the whole children chain and can be accessed through the this.$store variable. So, very roughly, in a very simplified way, we would create a store, import it in the main app, and use it in a component in the following way:

//CREATE STORE 
//initialize state 
const state = { 
  msg: 'Hello!' 
} 
//initialize mutations 
const mutations = { 
  changeMessage(state, msg) { 
    state.msg = msg 
  } 
} 
//create store with defined state and mutations 
export default new Vuex.Store({ 
  state: state 
  mutations: mutations 
}) 
 
//CREATE VUE APP 
<script> 
  import store from './vuex/store' 
  export default { 
    components: { 
      SomeComponent 
    }, 
    store: store 
  } 
</script> 
 
//INSIDE SomeComponent 
<script> 
  export default { 
    computed: { 
      msg () { 
        return this.$store.state.msg; 
      } 
    }, 
    methods: { 
      changeMessage () { 
        this.$store.commit('changeMessage', newMsg);      
      } 
    } 
  } 
</script> 

The very logical question might arise: why create a Vuex store instead of just having a shared JavaScript file that imports some state? You can, of course, do that, but then you must make sure that none of the components can mutate the state directly. Being able to change the store attributes directly would, of course, be a lot easier, but then it might lead to errors and inconsistencies. Vuex provide a clean way of implicitly protecting the store's state of direct access. And, it's reactive. Putting all this in statements:

  • The Vuex store is reactive. Once components retrieve a state from it, they will reactively update their views every time the state changes.
  • Components are not able to directly mutate the store's state. Instead, they have to dispatch mutations declared by the store, which allows easy tracking of changes.
  • Our Vuex store thus becomes a single source of truth.

Let's create a simple greetings example to see Vuex in action.

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

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