Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Caching the Current Folder Structure Using Vuex Chapter 6

We also need to create a mutation to allow the path to be updated from the hash of the


URL. Add a mutations object to the store and move the updateHash function from the


Vue instance—don't forget to update the function to accept the store as the first parameter.


Also, change the method so it updates state.path rather than this.path:


const store = new Vuex.Store({
state: {
path: ''
},
mutations: {
updateHash(state) {
let hash = window.location.hash.substring(1);
state.path = (hash || '');
}
}
});

By moving the path variable and mutation to the store, it makes the Vue instance
significantly smaller, with both the methods and data objects being removed:


const app = new Vue({
el: '#app',

store,
created() {
this.updateHash()
}
});

We now need to update our app to use the path variable from the store, instead of on the


Vue instance. We also need to ensure we call the store mutation function to update the


path variable instead of the method on the Vue instance.


Updating the path methods to use store commits


Start with the Vue instance, changing this.Updatehash to


store.commit('updateHash') instead. Don't forget to also update the method in the


onhashchange function. The second function should reference the store object on our


Vue instance, rather than the store directly. This is done by accessing the Vue instance


variable, app, and then referencing the Vuex store in this instance.

Free download pdf