我正在使用Github的Vue js样板之一开发Chrome扩展程序。默认样板设置如下:
store / index.js
import Vue from 'vue';
import Vuex from 'vuex';
import mutations from './mutations';
import * as actions from './actions'; // all actions are imported as separate vars
Vue.use(Vuex);
export default new Vuex.Store({
state: { },
mutations,
actions
});
然后在 actions.js
中import * as types from './mutation-types';
export const setFoo = ({ commit }, payload) => {
commit(types.SET_FOO, payload); // SET_FOO is defined in the mutation-types file
};
我认为上述方法缺乏我们想要使用突变类型文件的根本原因-避免为突变和动作重新命名。
因此,我想出了另一种方法:
store / index.js
...
import actions from './actions'; // actions are imported as separate functions
...
然后在 actions.js
中import * as types from './mutation-types';
export default {
[types.UPDATE_FOO] ({commit}, payload) {
commit(types.UPDATE_FOO, payload);
}
}
然后在扩展名中的任何地方,我们也可以使用const名称导入突变类型并调度动作,如下所示:
store.dispatch(types.UPDATE_FOO, 'some value');
第二种方法在命名,然后分派/提交我们的动作/变异方面似乎更为实用。还是最新版本可能有任何问题?
以上哪种方法通常会更好?
答案 0 :(得分:1)
第一种方法更可取,但这完全取决于您。官方Vuex
文档中使用了类似的方法。
Refrence
// mutation-types.js
export const SOME_MUTATION = '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
}
}
})
// actions.js
actions: {
checkout ({ commit, state }, products) {
// save the items currently in the cart
const savedCartItems = [...state.cart.added]
// send out checkout request, and optimistically
// clear the cart
commit(types.CHECKOUT_REQUEST)
// the shop API accepts a success callback and a failure callback
shop.buyProducts(
products,
// handle success
() => commit(types.CHECKOUT_SUCCESS),
// handle failure
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}