actions和
mutations,同时具有单个单独的操作文件,那么仍然可以正确识别该文件。项目结构
vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:
应用层级的状态应该集中到单个 store 对象中。
提交mutation是更改状态的唯一方法,并且这个过程是同步的。
异步逻辑都应该封装到action里面。
只要你遵守以上规则,如何组织代码随你便。如果你的 store 文件太大,只需将 action、mutation 和 getter 分割到单独的文件。
对于大型应用,我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例:
├── index.html
├── main.js
├── api
│ └── ... # 抽取出API请求
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 我们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块下面用是实例说一下怎么使用
一、在Nuxt项目的store目录下新建一个index.js文件,这样项目就启用了vuex
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)
const store = () => new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment (state) {
state.counter++
}
}
})
export default store
一般这个文件我们只作为vuex的入口文件,不在这里面写业务代码,其他的功能写在其他的vuex文件中,在index中导入一下即可
二、在store文件夹里再新建一个filter.js文件,在index.js中引入一下,这个文件来写我们的业务代码
filter.js文件
const state = ({
value: 'Hello World',
list: [1, 2, 3, 4, 5]});
const getters = {
include: (state) => (val) => {
return state.list.indexOf(val) > -1;
}
}
;
const mutations = {
SET_VALUE(state, value) {
state.value = value;
}
};
const actions = {
async getInfo({state, commit}, val) {
commit('SET_VALUE', val);
}
};export default {
namespaced: true,
state,
getters,
actions,
mutations
};
这个文件中输出时候的namespaced属性,如果为true时,使用这个文件的方法时,需要标注namespace,不写或为false时,则可以直接使用,这里建议使用namespaced,因为大型项目可能有很多复杂的业务,可能命名冲突,使用namespaced可以把方法区分开,避免很多问题










