vue2中使用vuex全面解析
初入前端写的是vue2,近些年一直在做vue3的项目,久未接触过vue2的代码了,今日突然维护了一个v2项目记忆已不似当年,今日对我以往所有接触的vuex使用做个总结。
vue2中使用vuex基础模板
store文件夹下的index.js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import Vue from 'vue' import Vuex from 'vuex' import modName from './mod' Vue.use(Vuex) export default new Vuex.Store({ state: { name:'蔡徐坤', age:'一坤年', sex:'男' }, getters:{ getDescripton(state){ return state.name+state.age+state.sex }, }, mutations: { getNewName(state,data) { state.age++; state.name=state.name+data } }, actions: { async getUserInfo(context,url){ const res = await axios.get(url) context.commit('getNewName',res) }, }, modules: { mod } })
|
mod.js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| export default{ namespaced: true, state:{ modName:'mod蔡徐坤'; }, mutations: { getNewName(state,data) { state.age++; state.name=state.name+data } }, actions: { async getUserInfo(context,url){ const res = await axios.get(url) context.commit('getNewName',res) }, }, getters:{ getDescripton(state){ return state.name+state.age+state.sex }, }
|
页面使用
取state值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| this.$store.state.name this.$store.state.mod.modName
computed:{
...mapState(['name']) ...mapState({newName:'name'}) ...mapState({newName: state => state.name,})
...mapState('mod', ['modName']), ...mapState('mod', {'newModName': 'modName'}) ...mapState({newModName: state => state.newModName.modName,}) }
|
取getter值
1 2 3 4 5 6 7 8 9 10 11 12 13
| this.$store.getters.getDescripton this.$store.getters.mod.getDescripton
computed:{
...mapGetters(['getDescripton']) ...mapGetters({mewGetDescripton:'getDescripton'})
...mapGetters('mod',['getDescripton']) ...mapGetters('mod',{mewGetDescripton:'getDescripton'}) }
|
mutations修改值
1 2 3 4 5 6 7 8 9 10 11 12 13
| this.$store.commit('getNewName', data) this.$store.commit('mod/getNewName', data)
methods: { ...mapMutations(['getNewName']), ...mapMutations({'NewGetNewName': 'getNewName'}) ...mapMutations('mod', ['getNewName']), ...mapMutations('mod',{'NewGetNewName': 'getNewName'}) }
|
actions修改值
1 2 3 4 5 6 7 8 9 10
| this.$store.dispatch('getUserInfo', url) this.$store.dispatch('mod/getUserInfo', getUserInfo)
methods: { ...mapActions(['getUserInfo']), ...mapActions({'newGetUserInfo': 'getUserInfo'}) ...mapActions('mod', ['getUserInfo']), ...mapActions('mod',{'newGetUserInfo': 'getUserInfo'}) }
|
麻了麻了……….