vue-vuex整理
1.结构不复杂时的结构和用法
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { userCode:'admin', }, mutations: { saveUserCode(state,userCode){ state.userCode=userCode } }, actions: { changeUserCode(context,userCode){ //这里可以执行异步操作,从接口获取数据 // return new Promise((resolve,reject)=>{ // login().then(...... resolve()).catch(err=>reject()) // }) context.commit('saveUserCode',userCode) } }, modules: { }, getters:{ userCode:state=>state.userCode } })
computed:{ userCode(){ return this.$store.state.userCode } }, mounted(){ console.log(this.$store.getters.userCode) }, methods:{ changeUserCode(){ this.$store.dispatch('changeUserCode','user') } }
辅助函数的用法
import {mapState,mapActions,mapGetters} from 'vuex' export default { name:'index', computed:{ ...mapState(['userCode']) // ...mapGetters(['userCode']) }, mounted(){ // console.log(this.$store.getters.userCode) }, methods:{ ...mapActions(['changeUserCode']) } }
2.结构复杂时
新建文件夹user.js
const state={ userCode:'admin' } const actions={ changeUserCode(context,userCode){ //这里可以执行异步操作,从接口获取数据 // return new Promise((resolve,reject)=>{ // login().then(...... resolve).catch(err=>reject()) // }) context.commit('saveUserCode',userCode) } } const mutations={ saveUserCode(state,userCode){ state.userCode=userCode } } export default{ namespaced:true, state, actions, mutations }
import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user' Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules: { user }, getters:{ } })
调用
<template> <div> {{userCode}} <button @click='change'>修改</button> <button @click="changeUserCode('user')">修改2</button> </div> </template> <script> import {mapState,mapActions} from 'vuex' export default { name:'index', computed:{ // userCode(){ // return this.$store.state.user.userCode // } ...mapState({ userCode:state=>state.user.userCode }) }, mounted(){ console.log(this.$store.getters.userCode) }, methods:{ change(){ this.$store.dispatch("user/changeUserCode","user") }, ...mapActions('user',['changeUserCode']) } } </script>