Vuex

What is the

A mechanism to implement global state (data) management of components, which can facilitate data sharing between components.

Benefits of using Vuex to manage data:

A. Vuex centrally manages shared data for easy development and later maintenance;

B. Efficiently realize data sharing between components and improve development efficiency;

C. The data stored in VUEX is responsive. When the data is changed, the data in the page will be updated synchronously;

Basic use of Vuex

1. Terminal command steps

1. Open the terminal and enter vue UI

 

2. Set the manual configuration items

 

 

 

 

3. Set the function items

 

 

4. Create projects

 

2. Mian. Js input

1. Install the Vuex dependency package

npm i vuex 

Import the Vuex package

 import Vuex from 'vuex';

Vue.use(Vuex); 

Create a store object

1 const store = new vuex. store ({2 // state: {4 count: 0, 5}, 6});Copy the code

Mount the Store object to the vue instance

1 new Vue({ 2 el: '#app', 3 render: (h) => h(app), 4 router, 5 // Create shared data object, mount Vue instance 6 // all components, can directly obtain from store 7 store, 8});Copy the code

Core features of Vuex

State

Concept: Store data in a shared state

access

Mode 1: Original mode
main.js
1 import Vue from 'Vue' 2 import App from './ app. Vue '3 import Vuex from' Vuex '4 Use (App) 6 vue. use(vuex) 7 // instantiate a vuex 8 9 const store = new vuex.store ({10) State mutations Actions 11 state: {12 0, 14 15 }, 16 }) 17 18 Vue.config.productionTip = false 19 20 new Vue({ 21 render: $mount('# App '); $mount('# App ');Copy the code
Mode 1: Access in original mode

App.vue

1 <template> 2 <div id="app"> 3 <! {{this.$store.state.count}}</p> 5 <! -- 2.0 --> 6 <p> Compute attribute status :{{count}}</p> 7 </div> 8 </template> 9 10 <script> 11 export default {12 name: 'App', 13 computed: $store.state.count () {16 return this.$store.state.count 17}, 18}, 19 } 20 </script> 21 22 <style> 23 </style>Copy the code
Mode two, auxiliary function form

Import {mapState} from ‘vuex’

2. Then map the data to computed attributes: computed:{… MapState ([‘ global data name ‘])}

1 <template> 2 <div id="app"> 3 <! --> 4 <h2>state </h2> 5 <! {{count}}</p> 7 </div> 8 </template> 9 10 <script> 11 12 13 // auxiliary function 14 // MapState 15 import {mapState} from 'vuex' 16 export default {17 name: 'App', 18 components: {19 Addition, 20}, 21 // Define data in state in computed properties in components 22 // Reduce the amount of code in templates 23 computed: {24... mapState(['count']), 25 }, 26 } 27 </script> 28 <style> 29 </style>Copy the code

 

 

Mutation

The implementation of mutations, immediately get a view state, because it is immediately, so must be synchronous

access

Mode 1: Original form

main.js

1 import Vue from 'Vue' 2 import App from './ app. Vue '3 import Vuex from' Vuex '4 Use (App) 6 vue. use(vuex) 7 // instantiate a vuex 8 9 const store = new vuex.store ({10) State mutations Actions 11 state: {12 Mutations modify the value of state on articles16 Mutations must be simultaneously updated for the purpose of forming a data snapshot. 17 // Mutations is an object, which contains the method for changing state. {19 // modify the method 20 // the method name is custom, not necessarily called updateStae, 21 // the first parameter is the state attribute of the current store 22 // payload transport parameters, Open embolization, open embolization, open embolization, open embolization, open embolization, open embolization, open embolization, open embolization  27 updateStae(state, payload) { 28 state.count += payload 29 }, 30 }, 31 32 }) 33 34 Vue.config.productionTip = false 35 36 new Vue({ 37 render: $mount('# App '); $mount('# App '); $mount('# App ')Copy the code

 

Mode two, auxiliary function form
1 // On demand import mapMutations 2 import {mapMutations} from "vuex"; 3 <! SetMutations (3) > 4 <button @click="setMutations(3)">+1(auxiliary function form)</button> 5 export SetMutations maps the customized function setMutations in the mutations object to the current component 9... mapMutations(["setMutations"]), 10 11 } 12 }Copy the code
Print result:

Action

Mutations cannot write asynchronous code, which will cause the vUE debugger to display errors, and Action to perform asynchronous operations

Asynchronously modify the data, submit the data to mutations, and then modify the data

mian.js

1 import Vue from "vue"; 2 import App from "./App.vue"; 3 4 import Vuex from "vuex"; 5 6 Vue.use(App); 7 Vue.use(Vuex); 7 open mutations = new vuex. store ({open mutations = new vuex. store (open mutations = new vuex. store (open mutations = new vuex. store (open mutations = new vuex. store (open mutations = new vuex. store (open mutations = new vuex. store)) {17 // setMutations self-defined function, can be arbitrarily named 18 // the self-defined function in setMutations receive parameters 19 // Method 2 --2.3 setMutations, 20 setMutations(state, a) {21 state.count += a; 22}, 23}, //actions perform asynchronous operations, custom functions, receive 24 actions: { 25 setActions(context, params) { 26 setTimeout(() => { 27 context.commit("setMutations", params); 28}, 1000); 29}, 30}, 31}); 32 33 Vue.config.productionTip = false; 34 35 new Vue({ 36 store, 37 render: (h) => h(App), 38 }).$mount("#app");Copy the code
Mode 1: Original mode

child.vue

1 < button@click ="btnAsynchronous"> </ button@click ="btnAsynchronous"> </ button@click ="btnAsynchronous"> This.$store.dispatch("setActions", 111); 6},Copy the code
Mode two, auxiliary function form
1 < button@click ="setActions(222)"> 2 export default {3 methods: {4 5... mapActions(["setActions"]), 6 } 7 }Copy the code
Print the result

Click the result printed 1s after

Getter

Getter it only wraps the data stored in the Store and does not modify the data stored in the Store. When the data in the Store changes, the content generated by the Getter also changes

main.js

1 import Vue from "vue"; 2 import App from "./App.vue"; 3 4 import Vuex from "vuex"; 5 6 Vue.use(App); 7 Vue.use(Vuex); 8 9 const store = new vuex. store ({10 // state state of the shared data 11 state: {12 // state of the shared data 13 count: 0, 14 list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 15 }, 16 mutations: { 17 18 setMutations(state, a) { 19 state.count += a; 20 }, 21 }, 22 actions: { 23 setActions(context, params) { 24 setTimeout(() => { 25 context.commit("setMutations", params); 26}, 1000); 27 }, 28 }, 29 getters: { 30 filtersList(state) { 31 return state.list.filter((item) => item > 5); 32}, 33}, 34}); 35 36 Vue.config.productionTip = false; 37 38 new Vue({ 39 store, 40 render: (h) => h(App), 41 }).$mount("#app");Copy the code

Mode 1: Original mode

 1 

Getters original way: {{$store. Getters. FiltersList}}

Mode two, auxiliary function form

{{filtersList}}</p> 2 import {mapGetters} from "vuex"; 4 5 export default { 6 methods: { 7 8 computed: { 9 ... mapGetters(["filtersList"]), 10 }, 11 12 }}Copy the code
Print result:

modules

Purpose: split templates, the complex scene by module to separate

format

Exit default new vuex. Store({2 // state: used to save all public data) state: {}, 4 getters: {}, 5 mutations: {}, 6 actions: {}, 7 modules: {8 module name 1: {9 // namespaced is true, so use mutations, you must add the module name 10 namespaced: true, 11 state: {}, 12 getters: {}, 13 mutations: {}, 14 actions: {}, 15 modules: {} 16}, 17 mutations: {18 // namespaced is not written, the default is false, so when using mutations, you don't need to add the module name 19 state: {}, 20 getters: {}, 21 mutations: {}, 22 actions: {}, 23 modules: {} 24 } 25 } 26 })Copy the code

main.js

1 import Vue from 'Vue' 2 import App from './ app. Vue '3 import Vuex from' Vuex '4 Use (App) 6 vue. use(vuex) 7 // instantiate a vuex 8 9 const store = new vuex.store ({10) State mutations Actions 11 state: {12 Mutations modify the value of state 17 // The implementation of mutations, immediately get a view state, because it is immediately, Mutations must be simultaneously updated for the purpose of forming a data snapshot. 19 mutations is an object, and the object contains the method for modifying state. 20 mutations: {21 // modify the method 22 // the method name is customized, not necessarily called updateStae, 23 // the first parameter is the state attribute of the current store 24 // payload transport parameters, Open embolization, open embolization, open embolization, open embolization, open embolization, open embolization, open embolization, open embolization, open embolization  30 updateStae(state, payload) { 31 console.log(state) 32 state.count += payload 33 }, 34 }, 36 // Get a number from the back end and update it to the count of state 37 Actions: $store ($store) {getAsyancCount(context, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store, $store Parmas) {42 // make an asynchronous request, SetTimeout (() => {context.com MIT ('updateStae', parmas) 45}, 1000) 46}, 47}, 48 getters: {49 // prevent all vuex calculation attributes 50 filterList(state) {51 return state.list.filter((item) => item > 5) 52}, 53 token: (state) => state.user.token, 54 name: (state) => state.setting.name, 55}, 56 Modules: {57 // Set the subattribute of module 58 user: Vex.esm.js?2f62:460 [vuex] unknown mutation type: vex.esm.js?2f62:460 updateToken 61 namespaced: true, 62 state: { 63 token: '12345', 64 }, 65 mutations: { 66 updateToken(state) { 67 state.token = '67890' 68 }, 69 }, 70 }, 71 setting: { 72 state: { 73 name: 'vuex instance ', 74}, 75}, 76}, 77}) 78 79 vue.config. productionTip = false 80 81 new Vue({82 render: $mount('# App '); $mount('# App '); $mount('# App ');Copy the code

subraction.vue

1 <template> 2 <div> 3 <h3>modules Module </h3> 4 <! $store.state. Submodule. Properties - > < p > the user's token: {{$store. State. The user. The token}} < / p > < p > 6 quick access method: {{token}} < / p > < p > 7 site name: {{ $store.state.setting.name }}</p> 8 <! -- Mode 2, shortcut access mode --> 9 <p> Shortcut access mode: {{name}}</p> 10 <hr /> 11 < button@click ="updateToken"> Update the token of the submodule </button> 12 <button @click="updateToken"> </button> 13 <! MapMutations </button> --> 14 </div> 15 </template> 16 <script> 17 18 // import { mapGetters, mapMutations, createNamespacedHelpers } from 'vuex' 19 import { mapGetters, CreateNamespacedHelpers} from 'vuex' 20 mapMutations this is 21 const {mapMutations} = createNamespacedHelpers('user') 22 export default { 23 computed: { 24 ... mapGetters(['token', 'name']), 25 }, 26 methods: {27 // updateToken() {28 // // this. new store.com MIT ('updateToken') 29 // // Use path method 30 // this. code. store.com MIT ('user/updateToken') 31 //}, 32 // // MapMutations (['user/updateToken']), 34 // // 35 // text() {36 // this['user/updateToken']() 37 //}, 38... mapMutations(['updateToken']), 39 }, 40 } 41 </script> 42 <style scoped> 43 button { 44 margin: 10px; 45 } 46 </style>Copy the code