1:什么是vuex
Vuex是一个专门为vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的的方式发生变化。Vuex也集成到vue的官方调试工具devtools extension。
由于Vue SPA应用的模块化,每个组件都有它各自的数据(state),界面(view),方法(actions)。这些数据,界面和方法分布在各个组件中,当项目内容变得越来越多时,每个组件中的状态会变得很难管理。这时候就需要用到vuex了~~
Vuex安装
使用npm安装
npm install vuex --save
Vuex的配置如下
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store=new Vuex.Store({
state:{
},
mutations:{
},
getters:{
},
actions:{
}
})
export default store;
Vuex配置相关要点
1:state即全局数据源,在组件中使用state数据源的方式是$store.state.XXX,如下,这里isLoading是在state中声明的一个状态值
<div>
{{$store.state.isLoading}}
</div>
如果是在组件的script代码块状中使用state的状态值,则通过一下方式(注意,在子组件中不能通过
this.$store.state.isLoading这种方式直接改变状态值,下面会有介绍如何改变state状态值
)
console.log(this.$store.state.isLoading)
2:Getter
Getter是从state中派生出的一些状态,可以理解为是store的计算属性。getter的返回值会根据它的依赖被缓存起来。且只有当它的依赖值发生了改变才被重新计算。
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
在组件中使用getter的方式如下
this.$store.getters.doneTodos
3:mutations
更改Vuex的store中的状态的唯一方法是提交mutation。mutation非常类似于事件,每个mutation都有一个字符串的事件类型和一个回调函数。这个回调函数就是我们实际进行状态更改的地方,并且它会接受state作为第一个参数
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
在组件中通过提交mutations的方式来改变store中的状态值,提交方式如下
this.$store.commit('increment')
提交载荷
你可以向store.commit传入额外的参数,即mutation的载荷
const store=new Vuex.Store({
state:{
isLoading:false//这里每个状态值在子组件中都可以通过this.$store.state.XX进行访问
},
mutations:{
increment(state,flag){
state.isLoading=flag
}
}
})
在大多数的情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的mutation会更易读。
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
在组件中以对象风格的提交方式如下
this.$store.commit({
type: 'increment',
amount: 10
})
既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:
最好提前在你的 store 中初始化好所有所需属性。
当需要在对象上添加新属性时,你应该
使用
Vue.set(obj, 'newProp', 123)
, 或者以新对象替换老对象。例如,利用 stage-3 的对象展开运算符我们可以这样写:
state.obj = { ...state.obj, newProp: 123 }
注意,mutation必须是同步函数
4:Action
action类似于mutation,不同在于:
Action通过提交mutation来变更状态,而不是直接变更store中的状态,action可以包含任意异步操作,actions接收context作为第一个参数,context是与store实例具有相同方法和属性的对象,可以通过context.state和context.getters来获取state和getters。
const store=new Vuex.Store({ state:{ isLoading:false//这里每个状态值在子组件中都可以通过this.$store.state.XX进行访问 }, mutations:{ updateLoadingState(state,flag){ state.isLoading=flag } }, actions:{ onLoading(context,flag){ context.commit("updateLoadingState",flag); } } })
在组件中提交actions和提交mutations的方法不同,使用如下
this.$store.dispatch("onLoading",true);
5:Module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store对象就有可能变得相当臃肿。所以Vuex允许我们将store分割成模块。每个模块拥有自己的state,mutation,action,getter甚至是嵌套子模块,从上至下进行同样方式的分割
const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } })
以上就是vuex相关基础知识点~~