vuex使用store对象管理共享状态,也就是全局变量
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store = new Vuex.store({
namespaced: true, // 命名空间
state: {},
mutaions: {},
getters: {
infoData(state, getters) {
return (xxxx) => {} //可以返回函数 这样可以传入参数来使用
}
},
actions: {},
modules: {}
})
export default store
vuex的5个属性及作用分别是:
- state:用来存放多个组件会用到的公共属性
- mutations:改变state的规范途径,并且只能同步操作,可以在vue-devtools 追踪到修改记录
- getters:作用和computed相似,对state里面的多个属性计算时使用
- actions:一些对state的异步操作可以放在actions中,并通过在action提交到mutaions进行状态的修改
- modules:当store对象过于庞大时,可以根据具体的业务需求分为多个module
state 读取数据
// 普通读取 主模块
this.$store.state.token
// 辅助函数
computed: {
// 注解:mapState(["total"]) 调用返回对象并解构 ...{ total() {} }
// 获取vuex总仓库的属性
...mapState(['token','userInfo']),
// 获取有命名空间模块的属性
...mapState('permission', ['sildebarMenu','permissionList']),
// 获取分仓库的属性
...mapState({ // state为总仓库的数据,并重新命名
banners: state => state.home.banners,
})
}
mutations 同步提交数据
// 字符串
this.$store.commit("事件类型", msg)
// 对象
this.$store.commit({
type: '事件类型',
userInfo: {name: "sky", age: 20}
})
// 辅助函数
methods: {
// 普通调用
...mapMutations(['SET_TOKEN']),
// 命名空间调用
...mapMutations('模块名',['事件类型','事件类型'])
}
actions 异步修改state
// 字符串
this.$store.dispatch("事件类型", msg)
// 对象
this.$store.dispatch({
type: '事件类型',
userInfo: {name: "sky", age: 20}
})
// 辅助函数
methods: {
// 普通调用
...mapActions(['SET_TOKEN']),
// 命名空间调用
...mapActions('模块名',['事件类型','事件类型'])
}
context:{
state, 等同于store.$state 若在模块中则为局部状态
rootState, 等同于store.$state 只存在模块中
commit, 等同于store.$commit
dispatch, 等同于store.$dispatch
getters 等同于store.$getters
}
mutations: {
UPDATE_INFO(state,name) {
// 1.不存在state属性强制渲染
Vue.set(state.autors[2],'sex','女')
// 2. 存在的直接赋值即可
state.autors[2].name = name
}
}
actions: { //payload 解构赋值
UPDATE_INFO(context,{ name }) {
return new Promise((reslove,reject) => {
setTimeout(() => { // 模拟异步操作
context.commit('UPDATE_INFO', name)
reslove(payload)
//②调用resolve,响应给组件一些数据
},1000)
})
}
}
methods: {
updateInfo() {
//异步操作修改内容
this.$store.dispatch("UPDATE_INFO", {name: "sky",age: 18}).then((res) => {
console.log("接收相应回来的数据",res);
//③操作异步修改state后的数据
});
}
}