.NET MVC, Webpack and Vue.js — Final — Vuex.js
In this last story about the subject, I show how to keep the vue state between page reloads
- Part 1 — Tools;
- Part 2 — Project structure;
- Part 3 — NPM Packages;
- Part 4 — Webpack Configuration;
- Part 5 — Vue.js;
- Part 6 — Vuex;
Now that we have our application already running with Vue.js, we’ll set a configuration to keep state between pages reloading.
First, we have to install this npm package
npm install vuex-persist
This package will use browser database to store the Vuex state data.
After install, create a store.js file at root of the ~/public/src/js, and put the code:
Now, we have to import the store in the ~/public/src/js/home/index.js, adding the store to the Vue instance
Execute npm run build and run debug and see what you built.
Now, in the store.js, create a new state and a mutation for this state:
In the ~/public/src/js/home/index.js, import the mapState from vuex, it’ll map the anotherMessage state in the computed object and we have to create a method that commit the mutations from the store:
Add a button in the Home/Index.cshtml and bind the changeMessage method to the button with v-on:click=“” directive, add a <p> tag that show the anotherMessage state with double mustache sintax and add a link to about page:
Create a about directory in ~/public/src/js directory, create a index.js file, import the Vue, the mapState from Vuex and the store:
In the About.cshtml, create a div with the app-about id, and bind the anotherMessage to a <p> tag.
npm run build
Run debug, go to home, click on the button and go to about, see what’s happened.
Now, write your application with your needs. You can create any modules in the ~/public/src/js/<view-name>/<module>.js and import then in the index.js file. Vuex can be modular too, you can read about here.
My resources:
- Web Complete Course at Udemy (in portuguese, where I got my major knowledge about javascript and webpack);
- Setting up ES6 Modules for MVC 5;
- Vue.js and ASP.NET MVC;
- Vuex-Persist (I found the references at StackOverflow but I didn’t save the url);
- Webpack;
I want to thank all people which contributes with Vue, Webpack and all js frameworks and libraries. You’re doing a great work. I want to do that someday!
I appreciate your reading. Share this if it can be useful for you or someone that you know.
See ya in my next posts!
Thanks!