下面以一个简单的计数器应用为例,演示如何使用 Vuex
的 commit
方法来触发状态变更。
首先,在 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
的值,从而反映出最新的消息状态。