vuex:专为Vue.js应用程序开发的状态管理模式。
vue设置一个常量在其他地方使用
// 定义
const shareObj = {
name:'why'
}
// 全局
Vue.prototype.shareObj = shareObj
// 使用
console.log(this.shareObj.name)
Vuex的使用场景
在多个界面间的共享问题
- 用户的登录状态、用户名称、头像、地理位置信息等等
- 商品的收藏、购物车中物品等等。
状态显示在视图上,视图上可以进行一些行为,行为可以改变状态。
Vuex的使用
//(1)store/index.js文件下
import Vue from 'vue'
import Vuex from 'vuex'
// 1.安装插件
Vue.use(Vuex)
// 2.创建对象
const store = new Vuex.Store({
state: {
counter: 1000
},
mutations: {},
actions: {},
getters: {},
modules: {}
})
// 3.导出store共享
export default store
//(2)main.js文件下引入
import store from './store/index'
Vue.prototype.$store = store
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
//(3) 使用
$store.state.counter
Vuex状态管理图例
使用Mutations
修改State
的话,就可以使用Devtools
进行跟踪
state
Vuex的store中的state是响应式的,当state中的数据发生改变时,Vue组件会自动更新。
这就是要求我们必须遵守一些Vuex对应的规则:
· 提前在store中初始化好所需的属性
· 当给state中的对象添加新属性时,使用下面的方式:
- 使用
Vue.set(obj,'newProp',123)
Vue.delete(obj,'newProp')
2.用新对象给旧对象重新赋值
// 1.定义
state: {
counter
}
// 2.使用
$store.state.counter
state
单一状态树(单一数据源)
- 如果你的状态信息是保存到多个Store对象中的,那么之后的管理和维护等等都会变得特别困难。
- Vuex使用了单一状态树来管理应用层级的全部状态。
- 单一状态树能够让我们以最直接的方式找到某个状态的片段。而且在之后的维护和调试过程中,也可以非常方便的管理和维护。
mutations
更新Vuex中状态的唯一方式
基本使用
// 1.定义
// 写入方法
mutations: {
// 默认会传入state
increment (state) {
state.counter++
}
},
// 2.使用
add () {
// increment为mutations里定义的方法名
this.$store.commit('increment')
}
传递参数
increment (state, num) {
state.counter * num
}
// 1.普通的提交封装
addCount() {
this.$store.commit('incrementCount',count)
}
// 2.特殊的提交封装 这里的counter是一个对象
addCount() {
this.$store.commit({
type:'incrementCount',
count
})
}
mutations中的注意事项
Vuex要求我们Mutation中的方法必须是同步方法。
主要的原因是当我们使用devtools时,devtools可以帮助我们捕捉mutation的快照。
但是如果是异步操作,那么devtools将不能很好的追踪这个操作什么时候会被完成。
actions
Actions类似于Mutation,但是是用来替代Mutaion进行异步操作的。
使用
actions:{
// 默认传入context
aUpdateInfo(context,payload){
// updateInfo为mutations里的函数
context.commit('updateInfo')
console.log(payload)
}
}
// 在其他页面中使用
this.$store.dispatch('aUpdateInfo','传递参数的位置')
更复杂的使用
aUpdateInfo(context,payload){
// updateInfo为mutations里的函数
context.commit('updateInfo')
console.log(payload。message)
payload.success()
}
}
// 其他界面传入复杂参数
this.$store.dispatch('aUpdateInfo',{
message:'我是传递的参数',
success:() => {
console.log("已经完成了")
}
})
getters
// 作用相当于计算属性
getters: {
powerCounter (state) {
return state.counter * state.counter
}
},
// 需要传参时 返回一个函数 在函数里传参
more (state) {
return function (num) {
return state.counter * num
}
}
// 使用
$store.getters.poweCounter
modules
为了避免state数据变得臃肿,可以设置modules,modules中可以定义自己的state、mutations、actions、getters。
// 使用模块state中的属性
// `a` 为模块名称 `name`为模块内state中定义的属性
$store.state.a.name
// 使用模块中的mutations 和模块外的使用一样 ,一般方法名不重复
$store.state.commit('方法名','参数')
// getters的使用方法同一般情况
$store.getters.poweCounter
// actions 的使用方法同一般情况 但是context的范围一般为自己本模块
context.commit('updateInfo')