vuex使用

第一步要引入在main.js中引入 vuex

import Vuex from 'vuex'

第二步注册vuex组件

Vue.use(Vuex)

第三步实例化Store

state:保存的是原始数据,可以理解为需要共享的数据或状态,

getters:可以理解为是staore的计算属性,可以实现就store的计算,但是不能更改。例如你想知道两个值相加、相乘。都是非常不错的选择。

mutations:mutations中的方法可以对state中的数据进行改变。

action:action中的方法可以调用mutations中的方法,但不可修改state中的原始数据。action中的函数可以使用ajax的技术对服务器进行数据交互。并且可以在回调中使用commit调用mutations中的方法,例如通过context.commit(‘increment’, price)increment是需要调用mutations中的方法名,price是需要传入的参数。 mutations中的方法再去更改state的原始数据。

代码示例

let store = new Vuex.Store({
  state: {
    totalPrice: 0
  },
  getters: {
    getTotal (state) {
      return state.totalPrice*2
    }
  },
  mutations: {
    increment (state, price) {
      state.totalPrice += price
    },
    decrement (state, price) {
      state.totalPrice -= price
    }
  },
  actions: {
    increase (context, price) {
      context.commit('increment', price)
    }
  }
})

如何在组件中获得state数据?

在组件内部使用 this.$store.state.属性名即可。

实例代码:

   computed: {
      totalPrice () {
        return this.$store.state.totalPrice
      }
  如何在组件中使用getters内的方法?
computed: {
  getTotal () {
    return this.$store.getters.getTotal
  }
}

如何在组件中使用mutations内的方法?

 methods: {
      addOne () {
        this.$store.commit('increment', this.price)
      },
      minusOne () {
        this.$store.commit('decrement', this.price)
      }
    }

如何在组件中使用actions内的方法?

 methods: {
      addOne () {
        this.$store.dispatch('increase', this.price)
      }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值