Vuex官网:https://vuex.vuejs.org/zh/
Vuex是Vue.js应用程序的状态管理模式+库。它充当应用程序中所有组件的集中存储,其规则确保状态只能以可预测的方式进行变更。可以想象为一个“前端数据库”(数据仓库),让其在各个页面上实现数据的共享包括状态,并且可操作
Vuex分成五个部分:
- State:单一状态树
- Getters:状态获取
- Mutations:触发同步事件(触发状态改变事件)
- Actions:提交mutation,可以包含异步操作
- Module:将vuex进行分模块(可将vuex分为多个文件引用)
使用方式
安装
npm install vuex --save
创建store.js文件或者store模块(根据调用模块大小使用)
├─store
│ ├─index.js
│ ├─state.js
│ ├─actions.js
│ ├─mutations.js
│ └─getters.js
在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
index.js(store模块)
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
export default store
子文件中格式(以state为例)
export default{
namespaced:'state',
state:{
},
}
- 在main.js中导入并使用store实例 ```javascript import store from ‘./store’
new Vue({ store, }) ```