用一个例子告诉你Vuex store 如何使用。

下面以一个简单的计数器应用为例,演示如何使用 Vuexcommit 方法来触发状态变更。

首先,在 Vuex store 中定义一个名为 counter 的 state,用于存储计数器的值:

const store = new Vuex.Store({
  state: {
    counter: 0
  }
})

然后,在 Vuex store 中定义一个名为 increment 的 mutation,用于增加计数器的值:

const store = new Vuex.Store({
  state: {
    counter: 0
  },
  mutations: {
    increment (state) {
      state.counter++
    }
  }
})

最后,在组件中通过 this.$store.commit('increment') 来触发 increment 这个 mutation:

<template>
  <div>
    <p>当前计数器的值为:{{ counter }}</p>
    <button @click="handleClick">点击增加计数器</button>
  </div>
</template>

<script>
export default {
  computed: {
    counter () {
      return this.$store.state.counter
    }
  },
  methods: {
    handleClick () {
      this.$store.commit('increment')
    }
  }
}
</script>

在上述代码中,我们通过 computed 属性来绑定计数器的值,通过 methods 属性来定义点击按钮触发的方法 handleClick。在这个方法中,我们使用 this.$store.commit('increment') 来触发名为 increment 的 mutation,从而更新计数器的值。

这样,当用户点击按钮时,就会触发 increment mutation,从而增加计数器的值,并将更新后的值存储在 Vuex store 中。组件会通过 computed 属性自动更新计数器的值,从而反映出最新的计数器状态。

那么如何传参呢?继续看例子

当需要传递参数给 commit 方法时,可以将参数作为第二个参数传递给 commit 方法。下面是一个示例,演示如何在触发 mutation 时传递参数:

首先,在 Vuex store 中定义一个名为 updateMessage 的 mutation,用于更新一个名为 message 的状态:

const store = new Vuex.Store({
  state: {
    message: ''
  },
  mutations: {
    updateMessage (state, newMessage) {
      state.message = newMessage
    }
  }
})

然后,在组件中通过 this.$store.commit('updateMessage', 'Hello, Vuex!') 来触发 updateMessage 这个 mutation 并传递参数 'Hello, Vuex!' :

<template>
  <div>
    <p>当前消息:{{ message }}</p>
    <button @click="handleClick">点击更新消息</button>
  </div>
</template>

<script>
export default {
  computed: {
    message () {
      return this.$store.state.message
    }
  },
  methods: {
    handleClick () {
      this.$store.commit('updateMessage', 'Hello, Vuex!')
    }
  }
}
</script>

在上述代码中,我们通过 computed 属性来绑定 message 的值,通过 methods 属性来定义点击按钮触发的方法 handleClick。在这个方法中,我们使用 this.$store.commit('updateMessage', 'Hello, Vuex!') 来触发名为 updateMessage 的 mutation,并将 'Hello, Vuex!' 作为新的消息参数传递进去。

这样,当用户点击按钮时,就会触发 updateMessage mutation,'Hello, Vuex!' 更新到 message 的状态中。组件会通过 computed 属性自动更新 message 的值,从而反映出最新的消息状态。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值