A list,
Let’s take a look at a more professional introduction to Vuex:
Vuex is an application state management model developed specifically for Vue. It uses centralized storage to manage the state of all components of the application and rules to ensure that the state changes in a predictable way.
In short, Vuex manages the common data of all components like a global object. If you want to modify the data of this global object, you have to modify it in the way that Vuex provides (you can’t modify it in your own way).
Second, the advantages of
Vuex state management differs from using traditional global variables:
-
Vuex’s state store is responsive: when your component uses the Vuex state, all associated components automatically update the corresponding data once it changes, saving developers a lot of trouble.
-
Vuex’s state cannot be changed directly: it is easy to change Vuex’s state if it is a global object variable, but this cannot be done in Vuex, and changes must be done using commint mutations, the only solution Vuex provides. The advantage of this is that it is convenient for us to track every state change, which is very useful when debugging during development.
Three, the use of steps
1. Install Vuex
npm install vuex --save
Copy the code
2. The reference Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
Copy the code
3. Create a warehouse Store
To use Vuex, we create an instance store, which we call a repository, to manage our state.
// Create a store
const store = new Vuex.Store({});
Copy the code
4. Include modules
- State: Data structure that defines the State of the application, where the default initial State can be set.
- Getter: Allows components to fetch data from stores,
mapGetters
The helper function simply puts thegetter
Map to local computed properties. - Mutation: is the only method that changes the state in the store, and must be a synchronization function.
- Action: for submission
mutation
, rather than changing state directly, can include any asynchronous operation. - Module: You can split the store into modules. Each module has its own
state
,mutation
,action
,getter
, or even nested submodules
Vuex acts like a global object. Vuex uses a single State tree, with a single object State containing all the states of the entire application hierarchy. You can think of these states as a bunch of global variables and data.
1. State
Let’s say we have a global state where count has a value of 5. Then, we can define this as key and value in the state object, which we can use as global state. As follows:
// Create a store
const store = new Vuex.Store({
//state Indicates the status of the storage application layer
state: {count:5 // Total: 5}});Copy the code
2. Getters
It can be argued that,getters
Is the computed property of store, something likecomputed
And perform some filtering and transformation on the data in state
Assuming we want to derive a new state, newCount, from state.count, our getters are appropriate
Getters accepts state as its first argument
const store = new Vuex.Store({
//state Indicates the status of the storage application layer
state: {count:5 // Total: 5
},
getters: {newCount:state= > state.count * 3}});Copy the code
Get {{newCount}} from the component:
export default {
computed: {
newCount(){
return this.$store.getters.newCount; }}};Copy the code
3. Mutations
Vuex
Provide us with modification warehousestore
The only way to state in is through submissionmutation
, and must beSynchronization function
We defined a function called increment in mutations, and the body of the function is where we want to make the change
State is accepted as the first argument, and the second is a custom pass argument
const store = new Vuex.Store({
//state Indicates the status of the storage application layer
state: {count:5 // Total: 5
},
// mutations is the only way to modify the data in state
mutations: {increment(The state, the value){ state.count += value; }}});Copy the code
When we commit, the first parameter, “increment”, is the corresponding increment method in mutations, and the second parameter is the customized value. Such as:
methods: {
getVal(event) {
// Get the value of the current key
let value = event.target.dataset.value;
// Commit a mutation named increment by commit
this.$store.commit("increment", value); }}Copy the code
Get {{count}} from the component:
export default {
computed: {
count(){
return this.$store.state.count; }}};Copy the code
4. Action
- Used to submit
mutation
Instead of directly changing the state,Can contain any asynchronous operation - It is only through
action=>mutations=>states
, the process is operated by the following steps:
export default new Vuex.Store({
// Store data
state: {
obj: {},},//4. Apply the method in commit mutations
mutations: {
getParam(state, Object) {
//5. Modify the data in state
state.obj = Object}},//2. Accept methods and parameters passed by Dispatch
actions: {
getParamSync(store, Object) {
// Handle asynchronous operations
setTimeout(() = > {
//3. Commit a mutation named getParam via commit
// The action function accepts an instance of store, so you can call store.mit to submit a mutation
store.commit('getParam'.Object);
}, 1000)}}})Copy the code
And then we just call it that way in the component
methods: {
getVal() {
let name= 'xia';
let age= '26';
let sex= 'man';
//1. Pass the method getParamSync and multiple parameters {name,age,sex} to actions via dispatch
this.$store.dispatch('getParamSync',{name,age,sex})
}
}
Copy the code
5. Modules
As the complexity of the project increases, to facilitate the management of Vuex, it is generally divided into different modules based on functions for future management. Each module has its own state, mutation, action, getter, and even nested submodules
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import * as getters from './getters'
import moduleA from './module/moduleA' / / module A
import moduleB from './module/moduleB' B / / modules
Vue.use(Vuex)
export default new Vuex.Store({
actions,
getters,
state,
mutations,
modules: {
moduleA,
moduleB
}
})
Copy the code
Modulea. js/moduleb. js file
// Each module has its own state, mutation, action, getter, and even nested submodules
export default {
state: {
text: 'moduleA'
},
getters: {},
mutations: {},
actions: {}}Copy the code
And then we just call it that way in the component
<template>
<div class="demo">
<h1>{{getText1}}</h1>
<h1>{{getText2}}</h1>
</div>
</template>
Copy the code
computed: {
getText1(){
return this.$store.state.moduleA.text;
},
/ / or. mapState({getText2: state= >state.moduleB.text; })}Copy the code
Therefore, the state inside the module is local and belongs only to the module itself, so the external must be accessed by the corresponding module name.
V. The most simple Vuex project example
Use vuex grammar sugarmapMutations
andmapGetters
1. Store data
Dr. Ue file
import { mapMutations } from "vuex"; / / introduce mapMutations
export default {
methods: {
...mapMutations({
// Correlate changeNews with SET_NEWS in mutations
changeNews: "SET_NEWS"
}),
submit(){
// Submit a mutation named changeNews and pass in the parameter val
let val = 'test news';
this.changeNews(val);New codestore.com MIT ("changeNews", val);}}}Copy the code
2. Obtain data
B.v ue file
import { mapGetters } from "vuex"; / / introduce mapGetters
export default {
computed: {
// Use vuex to read data (getters.js)
// equivalent to this.$store.getters. News (vuex syntax sugar). mapGetters(["news"])},created() {
// Get the news data from getters
console.log(this.news); }}Copy the code
3. Store File directory structure
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import * as getters from './getters'
// Every time state is changed, log is printed on the console
import createLogger from 'vuex/dist/logger'
Vue.use(Vuex)
constdebug = process.env.NODE_ENV ! = ='production'
export default new Vuex.Store({
actions,
getters,
state,
mutations,
strict: debug, // Enable strict mode when debug=true (performance loss)
plugins: debug ? [createLogger()] : []
})
Copy the code
state.js
const state = {
news: {}}export default state;
Copy the code
mutations.js
const mutations = {
SET_NEWS(state, val) {
state.news= val
}
}
export default mutations;
Copy the code
actions.js
// Asynchronous processing
const actions = {
M_NEWS({ commit }, val) {
commit('SET_NEWS', val); // commit mutations}}export default actions;
Copy the code
getters.js
// usually get data from getters (this.$store.getters. News;)
export const news = state= > state.news // Do no other processing directly map out
Copy the code
4. Use the store
It is referenced in main.js
import store from './store' //vuex stores files
new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})
Copy the code