1, What is Vuex
vuex is composed of five core parts
1.state: used to store data
// Create a User component const User = { template: `<div>{{ User }}</div>`, computed: { // Calculation properties count () { return this.$store.state.count // this is the instance of the current vue and the instance of the component; //. $store means that vuex is registered in vue, so any global component can get the vuex; //this.$store is the object of vuex; //Just import vuex through import; // Then through vue.use our vuex, // We can get the object of our vuex through this.store // . state is the attribute defined in vuex and its only data source // Any of our states must be defined in our stort // count is an attribute in our state // This is how we use the states in vuex } } }
2.actions: asynchronous operations can be included, which is also used to store the method of modifying state, but action s are based on changes.
const store = new Vuex.Store({ // We new an example of vuex state: { // We define a state count: 0 }, mutations: { // Changes is the only one used to submit the count value increment (state) { state.count++ } }, actions: { // actions also defines increment; It receives a context by default; Context it can directly call the commit method // This is all registered by vuex globally // Through the context object, we can call our commit to submit an increment; After this sentence is executed, you will call the increment method in mutation, and the value of count will be + +; // increment (context) { context.commit('increment') } } })
3. Changes: the only place where the state data can be modified. For example, when the number of chestnuts, such as shopping carts, is greater than 99, we need to change it to "99 +"; At this time, you can't be satisfied with just defining a state; We need to extend a getters again to do such an operation;
const store = new Vuex.Store({ state: { // We define a state attribute in the Store count: 1 // It has a field such as count, and the value is 1 }, mutations: { // So how can we change count to another value? We have no other method, but we must use the value of mutations // How to submit, for example, we define a property such as changes, which contains an increment function, which can be used at will // The increment function first receives a status by default; The first parameter is state; This state is the state above // It can be through state. count to get our status value; Come and go, give it + +; To change its state // Note: functions can only be defined in mutations to submit changes to the values in state // What are the benefits of this method? It is equivalent to us managing our logs; Manage our records, where and how to submit them, and add them to our records at each step; Convenient debugging of vuex increment (state) { // Change status state.count++ } } })
//That is through store.commit('increment') //Submit this function so that our value can be increased by 1;
Bifang said that on our shopping cart list page, when we join the shopping cart, we only need to adjust store.commit to submit increment; Then our increment will increase the number of shopping carts + +; The number of shopping carts in each page will be + +; This is the function of our mutations.
Getters: calculate the state data (it will be cached). You can add "getters" and "states" (equivalent to the calculation attributes in the store) to obtain the value of shared variables. Some new states can be derived from getters; Let's look at the following example: we create a new instance of vuex. This way is to define the instance of vuex,
const store = new Vuex.Store({ // In this way, we create a vuex object, which includes state. We can extract any state and put it in state, // state is our only data source. We can see the array defined in it, which is called todos. Adding this todos is the array used for each page // Next, getters is also defined. Getters and state are level relations; // For example, five more pages now use this array, but there happens to be one page that doesn't fully apply this array, // It just wants to use an array list where done is true; // We can operate on arrays through getters; // We directly return state. Todos. Filter (todo = > todo. Done); Return data with todo.done as true through its filter filter // Getters is an extension of state. Some new states can be derived from getters // getters operates based on todos state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
modules: modular management store (warehouse). Each module has its own state, mutation, action and gette.
2, There are also some advanced syntax of vuex - modular data management
1. If our project is very large and there is a lot of information, we can use modular data management
export default{ namespaced:true,//When using a module, you must open the namespace state:{ users:'' }, getters:{ users(state){ return state.users } }, mutations:{ changeUsers(state,payload){ state.users=payload } }, actions:{ CHANHE_USERS({commit},payload){ commit('changeUsers',payload) } } }
2. Import the JS file of the sub module into the JS main file of vuex, import the module file in the index.js file, where the name of the module file is used as the access entry for createNamespacedHelpers, add the modules object to the vuex object, and register the sub module in modules
import Vue from 'vue' import Vuex from 'vuex' import rules from './modules/rules' import users from './modules/users' Vue.use(Vuex) export default new Vuex.Store({ //Register vuex module modules:{ rules, users } })
Using files in vuex
<script> import {mapActions,mapGetters,createName} from 'vuex' //To use createName, you need to add the named: true attribute in the module, where the module name of the js file of the parameter is imported let users=createName('users') let rules=createName('rules') export default { methods:{ ...mapActions(['CHUANGE_NUM']), // ...users.mapActions() }, computed:{ ...mapGetters(['c','d']), ...users.mapGetters(['users']), ...rules.mapGetters(['admin']) } } </script>
Function call containing namespace
$store.state.b.count $store.commit('b/addcount')
Vuex put it bluntly, it is like opening up the memory space shared by a component, which can be accessed and used by all components
We create a store folder in src and add one in it index.js To store the shared data, introduce the store file into main.js, and inject the store into the Vue instance.
main.js
import Vue from 'vue' import App from './App' import router from './router' import Vuex from 'vuex' import store from './store' Vue.use(VueRouter) Vue.use(Vuex) Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
Finally, take a vague look at the project structure
├── index.html ├── main.js ├── api │ └── ... # Extract API request ├── components │ ├── App.vue │ └── ... └── store ├── index.js # Where we assemble the module and export the store ├── actions.js # Root level action ├── mutations.js # Root level mutation └── modules ├── cart.js # Shopping Cart module └── products.js # Product module