之前整理了vuex的使用场景,现在开始学习学习怎么使用。我会根据官网api来重新学习一遍。
首先我们要安装vuex:
Npm install vuex –save
官网推荐的vuex结构:
├── main.js
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 我们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块
个人是比较喜欢这样:
├── main.js
├── components
│ ├── App.vue
│ └── ...
└── vuex
├── store.js # 我们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块
分模块我们先不管,所以直接建成的目录结构:
Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。这也意味着,每个应用将仅仅包含一个 store 实例。
Store.js里面:
import Vuex from 'vuex'
import Vue from 'vue'
import mutation from './mutation'
import actions from './actions'
import getter from './getter'
Vue.use(Vuex)const state = {
score: [50, 90, 40, 80, 65, 99, 30, 87]
}
export default new Vuex.Store({ state, getter, actions, mutation})
然后在main.js里面引入并使用:
这样,我们就搭建出了vuex最简单可以使用的结构了。
欢迎关注Coding个人笔记 公众号
网友评论