vuex有哪几种状态和属性?
有五种,分别是 State、 Getter、Mutation 、Action、 Module (就是mapAction等)
vuex的流程?
页面通过mapAction异步提交事件到action。action通过commit把对应参数同步提交到mutation。mutation会修改state中对应的值。
最后页面通过getter获取到state里的值,在页面的计算属性中,通过mapGetter来动态获取state中的值。
vuex的State特性是?
state就是存放数据的地方,类似一个仓库。
特性就是当mutation修改了state的数据的时候,他会动态的去修改所有的调用这个变量的所有组件里面的值(若是store中的数据发生改变,依赖这个数据的组件也会发生更新)
vuex的Getter特性是?
getter用来获取数据,mapgetter经常在计算属性中被使用
vuex的Mutation特性是?
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作
vuex的优势
状态管理工具的核心是响应式的做到数据管理一个页面发生数据变化,动态的改变对应的页面。
相比使用localStorage ,localstorge只能纯属字符串数据格式,因此还得封装自己的写入写出,localstorage的优势是永久存储。
dispatch 和 commit 的区别与使用(vue2中使用)
1.dispatch 异步操作
this.store.dispatch('actions的方法', arg), 调用actions里的方法。
2.commit 同步操作
this.store.commit('mutations的方法', arg),调用mutations里的方法。
computed: {
businessInfo() {
return this.$store.getters['globe/user/businessInfo']
},
},
vue2中使用方法步骤:
const user = {
// 初始化store对象
state: {
token: ''
},
// 异步操作放到action handler里,通过commit把对应参数同步提交到mutation
actions: {
// 登录
Login({commit}, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo.account, userInfo.password).then(aa => {
if(aa.status==200){
const tokenSuccess = aa.data.token.tokenValue
commit('SET_TOKEN', tokenSuccess )
document.cookie=`cookie地址`;
token="test"+tokenSuccess ;
//setToken("test" +token)
resolve();
}
}).catch(error => {
console.log("登录失败")
reject(error)
})
})
},
}
// 根据commit更新store,mutation会修改state中对应的值
mutations: {
SET_TOKEN: (state, token) => {
state.token ="test " +token
},
},
// 页面通过getter获取到state里的值
getters: {
token(state) {
return state.token
},
}
}