vuex vue的状态管理器
//一般分为 state getter mutation action
创建model
创建一个login文件
// state
const state = {
number: 10,
}
const getters = {
number: (state) => state.number
}
// n为传递的参数
const mutations = {
add(state, n) {
state.number += n
},
}
// action为触发mutation
const actions = {
actionAcc: async ({ commit, getters }, n) => { //可传入getter state
commit('add', n)
},
}
//导出
export default {
namespaced: true,
state,
mutations,
getters,
actions
}
//接收的index.js
// cnpm i -S vuex-persistedstate
import Vue from 'vue'
import Vuex from 'vuex'
import login from './login'
import persistedState from 'vuex-persistedstate' //保存刷新后的状态vuex
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
login
},
getters,
plugins: [ //状态可以持续保存,添加即可
persistedState({ storage: window.sessionStorage })
],
})
export default store
//vue 页面
import { mapState, mapMutations, mapGetters, mapActions } from "vuex";
//mapstate和mapgetter在computer使用,在后续方法里可以直接 this.num ,this.number
computed: {
...mapState("login", {
nums: state => state.number
}),
...mapGetters("login", ["number"]),
},
//mapmutation和 mapActions 在methods使用
// <div class="off" @click="cut()">挂断</div>
methods:{
// 声明mutation和actions
mapMutation
...mapMutations(["login/add"]),
...mapActions(
["login/actionAcc"]
),
cut(){
console.log(this.number,this.nums) //这两个结果是相同的
this["login/add"](3); // 调用mutation 3为传递的参数
this["login/actionAcc"](4); //调用action 4为传递的参数
}
}