一、vuex的作用
提供一个在多个组件间共享状态的插件。需要共享状态的有用户登录状态、用户名称、头像、地理位置信息等等。
二、使用步骤
1.在src文件中创建一个文件夹store,并且在其中创建一个index.js文件
在index.js中写入以下代码:
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
})
export default store
2.在main.js文件,导入store对象,并放在new Vue中
代码如下(示例):
import store from './store/index'
new Vue({
el: "#app",
router,
store,
render: h => h(App)
});
3.具体使用
this.$store.state.变量名 //访问状态
this.$store.commit(mutation中的方法)//修改状态
三、vuex核心概念
1.state
如果状态信息是保存到多个
Store
对象中的,那么之后的管理和维护等等都会变得特别困难。所以
单一状态树用来管理应用层级的全部状态。(即共享状态信息)
2.getters
从store中获取一些state变异后的状态,getters默认是不能传递参数的,如果希望传递参 数,那么只能让getters本身返回另一个函数。
//从下面的store中获取学生年龄大于20的个数
const store = new Vuex.Store({
state: {
students: [
{ id: 110, name: 'why', age: 18 },
{ id: 111, name: 'why1', age: 19 },
{ id: 112, name: 'why2', age: 16 },
]
},
getters: {
getAgeCount: state => {
return state.students.filter(s => s.age >= 20).length
}
}
//传递参数,根据ID获取用户信息
getters: {
stuById: state => {
return id => {
return state.students.find(s => s.id === id)
}
}
}
3.mutation
提交mutation是store状态更新的唯一方式,通过mutation更新的数据携带的参数被成为载 荷(Payload)
mutations: {
increment(state, n){
state.count += n;
}
}//mutation的定义方式
store.commit('increment', 10);//通过mutation更新
当有很多参数需要传递时,以对象形式
mutations: {
increment(state, payload)
state.count += payload.amount;
}
}
store.commit('increment', {amount: 10});
4.action
类似于mutation,用来代替mutation进行异步操作
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state){
state.count++;
}
},
actions: {
increment(context){
context.commit('increment');
}
}
})
5.module
Vuex允许我们将store分割成模块(Module), 而每个模块拥有自己的state、 mutations、actions、getters等
const moduleA = {
state: { count: 0},
getters: {
doubleCount(state){
return state.count * 2;
}
},
mutations: {
increment(state){
state.count ++ ;
}
},
}