VueX 的简单使用 链接
VueX modules 模块化开发:
在项目庞大、数据繁多的情况 直接使用 VueX 会显得数据太多,代码太臃肿 ,不利于后期的维护,这时就应该考虑模块化开发了!
如何使用模块化
文件目录:
1、Vuex中定义模块
每个模块中都有 state 、 actions 、mutations、 getters
模块中定义 namespaced : true 开启命名空间
user模块内容:
//用户模块
export default {
namespaced: true, // 开起命名空间。
state: {
//用户ID
userid: 504334023,
name: "秃驴"
},
actions: {
set_user({ commit }, val) {
commit("set_user", val)
}
},
mutations: {
set_user(state, val) {
state.userid = val;
}
},
getters: {
setUser(state) {
console.log(1);
return state.userid + '秃驴飞'
}
}
}
@/store/index.js :
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
import createPersistedState from 'vuex-persistedstate'
// user 用户模块!!!
import user from "./modules/user"
const store = new Vuex.Store({
modules: {
user
},
plugins: [createPersistedState({
storage: sessionStorage,
key: "vuex"
})]
})
export default store
2、在组件中如何使用模块中的数据
// 用户ID: 504334023
<div class="home">
<span>
用户ID: {{ $store.state.user.userid }}
</span>
</div>
<script>
export default {
created(){
console.log(this.$store.state.user.userid); // 504334023
}
}
</script>
3、在组件中如何调用模块中 mutations 的方法
注意 : commit 里面的参数 "user/setUserId" ,不是或者的意思!!!
而是 user 模块中的 setUserId 方法 !!!
<div class="home">
用户ID: {{ $store.state.user.userid }} // 504334023
<button @click="onClick">点我</button>
</div>
<script>
export default {
created(){
console.log(this.$store.state.user.userid);
},
methods:{
onClick(){
// 注意: 这里 “user/setUserId” 不是或者的意思!!! 是user下的setUserId
this.$store.commit("user/setUserId", 123456);
}
}
}
</script>
Vuex 模块化-------辅助函数(语法糖)
如何使用 mapState , mapMutations, mapActions , mapGetters 辅助函数?
1、在组件中引入辅助函数
可以使用 createNamespacedHelpers 这样写
<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import {createNamespacedHelpers} from 'vuex'
// user 模块
const {
mapState:mapStateUser,
mapActions:mapActionUser,
mapMutations:mapMutaionUser
} = createNamespacedHelpers('user')
// cart 模块 可以引入多模块
const {
mapState:mapStateCart,
mapActions:mapActionCart,
mapMutations:mapMutaionCart
} = createNamespacedHelpers('cart')
export default {
}
</script>
因为我吧 mapState 这些辅助函数都使用 es6 语法中的解构赋值了 所以下面都是用的 ...mapState***() ...mapGetter***() ...mapMutation***() ...mapAction***()
2、如何使用 ...mapState***() ...mapGetter***()
在计算属性 computed 中进行扩展使用 ...mapState***() ...mapGetter***()
<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
computed:{
...mapStateUser(['userid','name']),// 数组形式
...mapStateUser({userid:'userid',name:'name'}), // 对象形式
...mapStateUser({uid:'userid',username:'name'}),// 对象形式下 改变映射
...mapGetterUser({userid:'setUser'}),
}
}
</script>
模板直接使用 userid 即可
<template>
<div class="home">
{{ userid }} // mapStateUser
{{ name }} // mapStateUser
</div>
</template>
3、如何使用 ...mapMutation***() ...mapAction***()
嗯.... 我不说你也知道的对吧!