What Vuex that?
- Vuex is a specially developed for Vue.js application status management database
- Status of all components using centralized storage management application, and a regular response state to ensure a predictable manner changes
- You can use debugging tools for debugging devtools
- Vuex draws Flux, Redux ideas
Vuex state storage is responsive to; Vue assembly when the state read from the store, the store if the state has changed, then the corresponding components will get updated efficiently.
Not be modified directly in a state store, change the only way is to store the state of submission (commit) a mutation, so that we can easily track changes in each state
Way data flow concept
way data flow using an embodiment to upload data stream and a downlink data stream for two-way data communication between two independent data streams. Way data flow means: the state can only be modified from one direction.
Vuex five core concepts
- state: the application data source, i.e. the state, state tree single
- getter: After processing the dependent data, the return value is cached according dependency, it will be recalculated only when the change occurs dependent
- mutation: The only way to change the status of the store is to submit mutation, it must be synchronized using store.commit submitted;
- action: asynchronous operation triggered by store.dispatch method of action, and then submit mutation, rather than directly change state
- module: The store is divided into modules (module), each module has its own state, getter, mutation, action to achieve a separate management application service module data
Vuex use the steps
The first step:
install Vuex
npm install vuex --save or yarn add vuex
Step two:
the src folder store new folder to the file entry index.js as vuex
// 1. 引入vuex及依赖文件Vue
import Vue from 'vue'
import Vuex from 'vuex'
// 2. 使用 Vuex 插件
Vue.use(Vuex);
// 初始化 状态数据
const state = {};
// 实时监听 state 的变化, 提供处理后的数据
const getters = {};
// 定义更改 state 状态的方法
const mutations = {};
// 异步操作方法
const actions = {};
// 3. 创建 store 仓库
const store = new Vuex.Store({
state,
getters,
mutations,
actions
});
// 4. 向外提供实例化的 store 对象, 用于注入整个应用
export default store;
The third step:
to create a good store warehouse, injected into the root instance object in Vue
import store from './store';
new Vue({
render: h => h(App),
store
}).$mount('#app');
// 注意:
// 现在就可以在每个组件中获取到 store 中的状态了
State acquisition state and commit the changes in the component method
// 在组件中获取状态
this.$store.state
this.$store.getters
// 提交修改状态的方法
// 通过 commit 提交同步操作的 mutation 方法
this.$store.commit("mutation中的方法名", payload);
// 通过 dispatch 派发 action 异步操作, action 内部 commit 提交 mutation 来修改状态
this.$store.dispatch("action中的方法名")