Vuex is a state management mode developed specifically for Vue.js applications.
store: data center
module: data model
index: instantiation
Directory Structure
Global Vuex
Rules of Use
Page data (various query parameters, result array obtained by api) are abstracted and placed in state.
Vue page is initialized, active dispatch triggers Action to request API data.
After Actions obtains the API data, use synchronous commit to trigger mutations to update the state.
The Vue page uses calculated properties to bind the data in the state and update the view synchronously.
Vue page parameter changes, use synchronous commit to trigger mutations to update state. Use dispatch to trigger Action to request API data again.
Related word learning
Vue=》dispatch=》Actions
Action=》commit=》Mutations (change)
Mutations=》mutate=》State
State=》render=》Vue
Vue=》commit=》Mutations (change)
Related grammar learning
Destructuring assignment
Analyze the structure, and then automatically assign values to simplify the programmer's code writing;
let obj={username:'java1234',age:31};
/*let username=obj.username; let age=obj.age;*/
let {username,age}=obj;
console.info(username,age);
Application example 1: User order query
store=》index.js
import Vuex from 'vuex';
import Vue from 'vue';
import orderList from './modules/orderList';
Vue.use(Vuex);
export default new Vuex.Store({
modules:{
orderList
}
})
store=>modules=>orderList.js
import Vue from 'vue';
const state={
orderList:[],
params:{}
}
//The page uses state by calling the store’s getters method
const getters={ getOrderList:state=>state.orderList }
//actions 异步
const actions={
fetchOrderList({commit,state}){
Vue.http.post('/api/getOrderList',state.params)
.then((res)=>{
//actions中使用commit调用mutations
commit('updateOrderList',res.data.list)
},(err)=>{
console.log(err)
})
}
}
//mutations synchronization
//vuex only allows mutations to modify state
const mutations={ updateOrderList(state,payload){ state.orderList=payload }, //page parameter changes are synchronous actions. updateParams(state,{key,val}){ state.params[key]=val } }
export default{
state,
getters,
actions,
mutations
}
vue => main.js
import store from './store';
new Vue({
el:"#app",
router,
store,
template:'<layout>',
components:{layout}
})
vue => views => orderList.vue
<template>
</template>
<script>
export default{ data(){ return{ } }, computed:{ //tableData list rendering data tableData(){ return this.$store.getters.getOrderList } }, methods:{ //productChange product drop-down selection box productChange(obj){ //Page parameters are changed, the mutation in the store is triggered by commit, and the mutation updates the parameters in the state synchronously. this.$store.commit('updateParams',{ key:'productId', val:obj.value })
//Asynchronous dispatch
this.$store.dispatch('fetchOrderList')
}
},
mounted(){ //When the page is rendered, the actions in the store are triggered by dispatch, and the actions are called asynchronously to obtain data. this.$store.dispatch('fetchOrderList') } } </script>
<style>
</style>
Application example 2: Login
Login page
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true
this.$store.dispatch('user/login', this.loginForm)
.then(() => {
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
this.loading = false
})
.catch(() => {
this.loading = false
})
} else {
console.log('error submit!!')
return false
}
})
}
Data center store=>modules=>user.js
import { login, logout, getInfo } from '@/api/user'
const actions = {
// user login
login({ commit }, userInfo) {
const { username, password } = userInfo
return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password }).then(response => {
const { data } = response
commit('SET_TOKEN', data.token)
setToken(data.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
}
export default {
namespaced: true,
state,
mutations,
actions
}
Login interface api/user
import request from '@/utils/request'
export function login(data) {
return request({
url: '/vue-element-admin/user/login',
method: 'post',
data
})
}
to sum up:
1. The Vue page is initialized. Mounted actively uses dispatch to trigger actions in the store, and actions asynchronously call API to obtain data.
2. Use commit to call mutations in actions.
3. The mutations modify the state synchronously.
4. Vue page view data binding calculation properties, get the state data in the store through the getters method, and render the page.
5. The parameters of the Vue page are changed, the mutation in the store is triggered by commit, and the mutation updates the parameters in the state synchronously. The page uses dispatch to trigger the actions in the store again to obtain new Api data.