Download vuex component library dependencies
npm install –save vuex
2. Basic steps of using VUEX:
Create a vuex.store
2. Register the Store object in Vue
This.$store.dispatch(‘ XXX ‘) calls the XXX method in the Actions object of store.js in vue
3, on the code
(1), App. Vue
<template><! <div> <p>click {{$store.state.count}} times, count is {{evenOrOdd}}</p> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="incrementIfAdd">increment if add</button> <button @click="incrementAsync">increment async</button> </div></template><script>export default { computed:{ evenOrOdd(){ return this.$store.getters.evenOrOdd } }, methods: {increment(){// notify vuex to add this.$store.dispatch('increment') // trigger the corresponding action in the store}, Decrement (){// notify Vuex to reduce this.$store.dispatch(' Decrement ') // Trigger the corresponding action in store}, IncrementIfAdd (){// notify vuex this.$store.dispatch('incrementIfAdd') // trigger the corresponding action in the store}, /* incrementAsync(){// notify vuex this.$store.dispatch('incrementAsync') // trigger the corresponding action in the store}, }}</script><style></style>Copy the code
(2), store. Js
/* store */import vuex from "vuex"; import Vue from "vue"; Vue.use(Vuex); /* const state = {// initialize state count: 0}; Mutations = {mutation INCREMENT(state) {state-.count ++; mutations = {mutation INCREMENT(state) {state-.count ++; }, // change DECREMENT(state) {state.count--; }}; Const actions = {// increment action increment({commit}) {// Commit increment(" increment "); }, decrement({commit}) {// commit reduced mutation COMMIT (" decrement "); }, incrementIfAdd({commit, state}) {if (state.count % 2 === 1) {// commit incrementIfAdd({commit, state}); }}, // Asynchronous action incrementAsync({commit}) {setTimeout(() => {// Commit increased mutation COMMIT ("INCREMENT"); }, 1000); }}; /* Const getters = {evenOrOdd(state) {return state.count % 2 === 0? "Even" : "odd "; }}; export default new Vuex.Store({ state, mutations, actions, getters});Copy the code
(3), the main js
import Vue from 'vue'import App from './App.vue'import store from './store'new Vue({ el: $store Components: {app}, template: '< app />'})Copy the code
App.vue methods#increment method as an example:
Increment calls the action in the store by this.$store.dispatch(‘increment’);
Increament in Actions passes INCREMENT through COMMIT, commit will call INCREMENT function of mutations, mutations will update the state, and finally the page display will change accordingly.