vue2 - vuex优化,vuex模块化 模块化操作数据
1.vuex优化
mapActions 在methods添加了 setter方法
mapMutations 在methods添加了 setter方法
mapGetters 在computed添加了 getter方法
mapState 在computed添加了 getter方法
import {mapActions,mapMutations,mapGetters,mapState} from 'vuex'
computed: {
//mapGetters 方式1 对象写法 自定义方法名称:映射的方法名称
...mapGetters({getId: "getId"}),
//mapGetters 方式2 数组写法 映射的方法名称
...mapGetters(["getId"]),
//mapState 方式1 对象写法 自定义属性名称:映射的属性名称
...mapState({id: "id"}),
//mapState 方式2 数组写法 映射的属性名称
...mapState(["id"])
}
methods: {
//mapActions 方式1 对象写法 自定义方法名称:映射的方法名称
...mapActions({setId: 'setId'}),
//mapActions 方式2 数组写法 映射的方法名称
...mapActions(["setId"]),
//mapMutations 方式1 对象写法 自定义方法名称:映射的方法名称
...mapMutations({SETID: "SETID"}),
//mapMutations 方式2 数组写法 映射的方法名称
...mapMutations(["SETID"])
}
2.vuex 模块化
必须要在每个模块中添加namespace: true属性,不然会报错
也可以把dog模块域cat模块单独的定义在一个文件中,export defautl暴露然后moon.js引入
定义moon.js:
import Vue from 'vue' //引入vuex import Vuex from 'vuex' //使用vuex插件 Vue.use(Vuex) //模块化 //关于dog的模块 const dog={ namespace: true, //异步操作 actions: { }, //state成员操作 mutations: { }, //加工state成员给外界 getters: { }, //state 存放状态 state: { } } //关于cat的模块 const cat={ namespace: true, //异步操作 actions: { }, //state成员操作 mutations: { }, //加工state成员给外界 getters: { }, //state 存放状态 state: { } } export default new Vuex.Store({ //使用模块化 modules: { //myDog: dog, //myCat: cat dog, cat } })
模块化之后如何调用方法与数据:map调用
<script> //引入mapActions import {mapActions,mapMutations,mapGetters,mapState} from 'vuex' export default { //mapGetters与mapState映射 computed: { //sate数组写法 ...mapState('dog',['name','age']), ...mapState('cat',['name','age']), //getters数组写法 ...mapGetters('dog',['lastName']), ...mapGetters('cat',['lastName']), //sate对象写法 ...mapState('dog',{name: 'name',age: 'age'}), ...mapState('cat',{name: 'name',age: 'age'}), //getters对象写法 ...mapGetters('dog',{lastName: 'lastName'}), ...mapGetters('cat',{lastName: 'lastName'}) }, //mapActions与mapMutations映射 methods: { //mapActions对象写法 ...mapActions('dog',{setName: 'setName'}), ...mapActions('cat',{setName: 'setName'}), //mapMutations对象写法 ...mapMutations('dog',{setName: 'SETNAME'}), ...mapMutations('cat',{setName: 'SETNAME'}), //mapActions数组写法 ...mapActions('dog',['setName']), ...mapActions('cat',['setName']), //mapMutations数组写法 ...mapActions('dog',['SETNAME']), ...mapActions('cat',['SETNAME']), } } </script>
模块化之后如何调用方法与数据:原生方法调用
<script> export default { methods: { mess(){ //Actions this.$store.commit(['dog/setName'],'levi') this.$store.commit(['cat/setName'],'levi') //Mutations this.$store.commit(['dog/SETNAME'],'levi') this.$store.commit(['cat/SETNAME'],'levi') //Getters this.$store.getters(['dog/lastName']) this.$store.getters(['cat/lastName']) //State this.$store.state.dog.name this.$store.state.cat.name } } } </script>
posted on 2023-02-18 13:58 Mikasa-Ackerman 阅读(124) 评论(0) 收藏 举报
浙公网安备 33010602011771号