【vuex】state、mutations、actions、getters

Vuex 是一个专为 Vue.js 开发的状态管理工具,可以实现组件间的数据共享。

1、state

state提供vuex中唯一的公共数据源,所有组件共享的数据都统一放到Store的state中存储。

假如我们需要把一个count数据要存到vuex中,以下代码即可:

  state: {
    count:0
  }

如何在组件中使用?

 第一种做法:

<h1> {{$store.state.count}} </h1>

第二种做法:使用vuex提供的mapState函数

    computed:{
        ...mapState(['count'])
    }
    // 等价于
    // computed:{ 
    //     count(){
    //         return this.$store.state.count
    //     }
    // }
<h1> {{showCount}} </h1>

2、mutations

mutations是vuex中唯一合法的用来修改state的方式,但是它不能进行异步操作

假如我们需要定义一个add方法,实现对state中的count加1

  mutations: {
    add(state){
      state.count++
    }
}

在组件中如何触发mutations中的add方法呢? 

第一种做法:

    methods:{
        add(){
            this.$store.commit('add');
        }
    }

第二种做法:

methods:{
        ...mapMutations(['add'])
    }

3、actions

actions用于处理vuex中的异步任务

假如我们需要在1秒后才执行mutations中的add方法,可以这样:

  actions: {
    addAsync(context){
      setTimeout(()=>{
        context.commit('add');
      },1000);
    }
}

在组件中怎么触发actions中的方法呢?

第一种做法:

    methods:{
        addNAsync(n){
            this.$store.dispatch('addNAsync',n)
        }
    }

第二种做法:

    methods:{
        ...mapActions(['addAsync'])
    }

4、getters

getters:对于state中的数据进行加工处理形成新的数据

  getters: {
    showCount(state){
      return '当前的count是:【'+state.count+'】';
    }
  }

在组件怎么使用?

第一种做法:

<h1> {{$store.getters.showCount}} </h1>

第二种做法: 

    computed:{
        ...mapGetters(['showCount'])
    }

    //template中
    <h1> {{showCount}} </h1>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值