我是vue的新手,虽然我的代码工作正常。我不确定这是不是故意的。是否有另一种更新vuex状态的方法,而不必调用.commit
并传入方法名称的字符串表示形式?这似乎是反直觉的。有一个我跑过去的指南,它传递给了一个{ commit }
对象的变异函数,但是这个语法似乎过于复杂了吗?这是我的代码。
存储
export const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
console.log(this.state.count)
},
decrement (state) {
state.count--
console.log(this.state.count)
}
}
})
计数器
<template>
<div class="counter">
<h1>{{ initialCount }}</h1>
<h2>{{ computedCounter }}</h2>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
</template>
<script>
import { store } from '../store/store.js'
export default {
name: 'Counter',
store: store,
data () {
return {
initialCount: store.state.count
}
},
computed: {
computedCounter () {
return store.state.count
}
},
methods: {
increment () {
store.commit('increment') <--- not a big fan.
},
decrement () {
store.commit('decrement') <--- also not a fan.
}
}
}
答案 0 :(得分:1)
recommended这样做的方法是使用常量变异类型,即:
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// actions.js
import * as types from './mutation-types'
const increment = ({ commit }) => {
commit(types.SOME_MUTATION);
};
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// we can use the ES2015 computed property name feature
// to use a constant as the function name
[SOME_MUTATION] (state) {
// mutate state
}
}
})