vuex的高级用法辅助函数和模块化

1辅助函数(又称语法糖)

分为四个

  • mapState
  • mapMutations
  • mapGetters
  • mapActions
2.当一个组件需要多个状态的时候,这些状态都声明成计算属性过于偏长于是就有了辅助函数
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'


computed:{
    ...mapState({
        a:"a",   //  "a" 指的是state中的a
        b:"b"
    }),
    ...mapGetters({
        Val:'newVal' // 可以重新命名
    })
}

methods:{
    ...mapActions({
        getSync:'getSyncNum'
    })

    ...mapMutations({
        increament:"increament"
    })
}



template

{{a}}  {{b}}

{{getSync(1)}}

<button @click='increament(1)'></button>
3.在vue页面中引入辅助函数
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
4.辅助函数注意事项
1.注意事项:
mapState与mapGetters推荐在计算属性里使用,可以直接做data数据使用

2. computed: {
    ...mapState(["shopData"]),
  },

3.其他辅助函数在methods里
  methods: {
    ...mapActions(["getData"]),
    ...mapMutations(["add"]),
  }
5.model模块化管理数据
  • 状态树结构复杂的时候,可以用modules进行管理
  • 多人协作开发,可以用modules,避免命名空间冲突
//创建store,分模块定义

const  test1 ={
    namespaced:true, //开启命名空间,在各组件总 ...mapState("test1",{name:"name"})
    state:{name:'test1'},
    actions:{},
    mutations:{
    changeName(state,arg){
            state.name=arg;
        },
    getters:{}
}

const test2 = {
    namespaced:true,
    state:{},
    actions:{},
    mutations:{
        
        }
    },
    getters:{}
}

new Vuex.Store({
    state:{name:"root"},
    actions,
    mutations,
    getters 
    modules:{
        test1,
        test2
    }

})


在组件中使用:

{{this.$store.state.name}}

{{name}}

{{this.$store.state.test1.name}}

{{tes1Name}}


computed:{
    ...mapState({
        name:“name"
    }),
    ...mapState('test',{   
        test1Name:'name'
    })
}
methods:{
    ...mapMutations('test1',['changeName'])
}
5.vuex超级篇,数据持久化

1.什么是数据持久化
刷新页面,数据丢失,清空,有时候我们需要把一些数据固话到本地,即使刷新也不能清空,例如:登录状态,token等
这是就需要到vuex数据持久化

2.安装

npm install vuex-persistedstate --save
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值