vuex 解析
2021-03-03 本文已影响0人
zhudying
vuex 是 Vue 配套的 公共数据管理工具,它可以实现数据的共享,在复杂的项目中避免了父子/子父/祖孙间通讯的复杂性,解决了复杂的网状通讯,实现了数据的单项流动。
- vuex的原理
![](https://img.haomeiwen.com/i12867526/0cc0d0af9aa723e3.jpg)
Vuex 实现了一个单向数据流,在全局拥有一个 state 存放数据,当组件要更改 state 中的数据时,必须通过 mutations中的方法进行修改,mutations 提供了订阅者模式供外部插件调用获取 state 数据的更新。
所有异步操作(常用于调用后端接口异步获取数据)或批量的同步操作需要走 actions,actions 通过触发 mutations 中的方法来修改 state 的数据。
数据变更后相应推送给组件,组件重新渲染到视图上。
vuex 是 vue 的状态管理器,存储的数据是响应式的。但是并不会保存起来,刷新之后就回到了初始状态,我们可以在 vuex 里数据改变的时候把数据保存到 localStorage/sessionStorage 里面,刷新之后如果 localStorage/sessionStorage 里有保存的数据,赋值给 store 里的 state。
- vuex的优点
- 能够在 Vuex 中集中管理共享的数据,易于开发和后期维护
- 能够高效的实现组件之间的数据共享,提高开发效率
- 存储在 Vuex 中的数据都是响应式的,能够实时保持数据与页面的同步
- vuex的使用(vue2.x)
- 安装vuex
npm install vuex --save
cnpm install vuex --save
- 导入 vuex
import Vuex from 'vuex'
Vue.use(Vuex) // 挂载
- 创建 store 对象
const store = new Vuex.Store({
state: { },
getters:{},
mutations:{},
actions:{}
})
export default store;
- 将 store 对象挂载到 vue 实例中
new Vue({
el: '#app',
render: h => h(app),
store
})
- 调用方法
// state
$store.state.xx
// getters
$store.getters.xx
// mutations
$store.commit('名称','参数')
// actions
$store.dispatch('名称','参数')
- 使用辅助函数 mapGetters/mapActions
- 创建store 对象
import Vue from "vue";
import Vuex from "vuex";
import getters from "./getters";
import user from "./components/user";
Vue.use(Vuex);
export default new Vuex.Store({
// 注册模块
modules: {
user
},
getters
});
- getter对象(getters.js)
const getters = {
name: state => state.user.name
};
export default getters;
- state数据(user.js)
import { logout } from '@/api/login';
const state = {
// 读取缓存数据
name: localstorage.getItem( 'name' ) || ''
};
const mutations = {
SET_NAME(state, name) {
state.name= name
// 缓存,避免刷新后重置
localstorage.setItem( 'TOKEN',state.name,)
}
};
const actions = {
// 登出
LOGOUT({ state, commit, dispatch }) {
return new Promise((resolve, reject) => {
logout().then(res => {
let { data } = res
commit('SET_NAME', '')
resolve(data)
}).catch(error => {
reject(error)
})
})
},
};
export default {
state,
mutations,
actions
};
- 使用 mapGetters/mapActions
import {mapActions, mapGetters } from 'vuex';
computed: {
...mapGetters(["name"]),
},
methods: {
...mapActions({
LOGOUT: 'LOGOUT'
})
}