Vuex{{this.$store.state.city}}

本文介绍如何使用Vuex进行状态管理,包括创建store、定义state、mutations和actions,以及如何在Vue项目中引入并使用store。同时讲解了通过actions进行异步操作的方法。

异步操作放在actions里面 或者说是 批量的同步操作也放在actions里面

actions需要用commit来调用mutation

cnpm install vuex --save

 创建store目录并在store目录下创建index.js

在main.js入口文件中引入,加入store

export default new Vuex.Store({
  state:{
    city : "天下"
  },
  actions:{
    changeCity(ctx,city){
      ctx.commit('changeCity',city)
    }
  },
  mutations:{
    changeCity(state,city){
      state.city = city
    }
  },
})
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

获取state的值

{{this.$store.state.city}}

state语法糖

    import {mapState} from 'vuex'

    computed:{
      ...mapState(['city'])
    }

调用actions

this.$store.dispatch('changeCity',city)

若没有actions的话直接使用commit来调用mutations

this.$store.commit('changeCity',city)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值