Vuex的基本使
1、安装vuex依赖包
npm install vuex --save
2、导入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
3、创建store对象
export default new Vuex.Store({
state: {
// 存储共享数据 映射到 computed ...mapState(["属性名"])
// 数据类型可以是 数值、字符串等基本类型,也可以是{}、[]、[{},{}]
// 不推荐直接操作,而应该使用 actions
},
getters: {
// 主要用对共享数据进行显示调整 1/2=>男/女
// 映射到 computed ...mapGetters(["属性名"])
},
mutations: {
// 直接操作 state 里的数据
// 映射到 methods ...mapMutations(["方法名"])
// 不推荐直接操作,而应该使用 actions
},
actions: {
// 间接操作 state 里的数据,通过调用 mutations 里的函数
// 映射到 methods ...mapActions(["方法名"])
},
})
4、将store对象挂载到vue实例中
new Vue({
el: '#app',
render: h => h(app),
router,
// 将创建的共享数据对象,挂载到Vue实例中
// 所有的组件,就可以直接从store中获取全局的数据了
store
})
Vuex的核心概念
Vuex中的主要核心概念如下:
1、State
在Vuex中,State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储,这里的Store相当于一个用于存储数据的公共容器。
const store = new Vue.Store({
state: {
count: 0
}
})
组件访问State中数据的第一种方式
this.$store.state.全局数据名称
去过是在html元素组件之间调用,则可以省略this,即:
<span>{{$store.state.全局数据名称}}</span>
组件访问State中数据的第二种方式
通过mapState辅助函数方式,实现组件访问State中数据的第二种方式
// 1. 从vuex中按需导入mapState函数
import { mapState } from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前的computed计算属性:
// 2. 将全局数据映射为当前组件的计算属性
computed: {
// ...表示展开映射,意思就是将全局属性映射为当前组件的计算属性
...mapState(['count'])
}
直接在调用获取组件属性
<span>{{count}}</span>
2 Mutations
Vuex中的Mutations是用于变更Store中的数据。
在Vuex中,只能通过mutations变更Store数据,不可以直接操作Store中的数据。虽然通过mutations的方式来操作数据,虽然繁琐了一点,但是却可以集中监控所有数据的变化。
例如需要让全局数据自增加1,则可以通过如下的方式在Mutations中定义
const store = new Vuex.Store({
state: {
user: {id: 1,name: "张三"}
},
mutations: {
info(state) {
return `编号:${state.user.id} 姓名:${state.user.name}`;
}
}
})
定义完mutations之后,下面就来介绍下Vuex的触发方式
触发mutations方式一
通过$store.commit()函数来触发mutations。
methods: {
handle1 () {
// 触发mutations的第一种方式
this.$store.commit('info')
}
}
接着就可以通过@click方法来调用handle1,从而来触发mutations函数。
另外,可以在触发mutations函数时,传入参数
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state) {
//变更状态
state.count++;
},
addN(state, n) {
state.count += n;
}
}
})
然后定义handler2
methods: {
handler2: {
this.$store.commit('addN', 5);
}
}
触发mutations方式二
通过导入mapMutations辅助函数来触发mutations。
// 1. 从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
...
// 2. 将制定的mutations函数映射为当前组件的methods函数
methods: {
// 将add和addN方法映射为methods中的函数,拱当前组件使用。
...mapMutations({'add', 'addN'}),
handleAdd() {
this.add();
},
handleAddN(n) {
this.addN(n);
}
// 或者直接在标签元素中直接@click=add()
}
对于mutations来说,只能够实现同步操作,不可以执行异步操作的。
3 Actions
从vuex官网中可以了解到,Actions类似于mutations,不同之处在于:
Actions提交的是 mutations,而不是直接变更状态。
Actions可以包含任意异步操作。
可以得出一个结论就是,如果通过异步操作变更数据,必须通过Actions,而不能使用Mutations,但是在Actions中还是要通过触发Mutations的方式间接变更数据。
如何定义Actions呢?
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state) {
//变更状态
state.count++;
},
addN(state, n) {
state.count += n;
}
},
actions: {
// 通过context去调用mutation
addAsync(context) {
setTimeout(() => {
context.commit('add'
}, 1000)
},
// 调用Actions是也可以传入参数
addNAsync(context, n) {
setTimeout(() => {
context.commit('addN', n);
}, 1000);
}
}
})
需要再次强调的是,只有通过mutation中定义的函数,才有权利去修改state中的数据,因此actions最终还是要调用mutation。
触发Actions的第一种方式
methods: {
handleAddAsync() {
this.$store.dispatch('addAsync');
},
handleAddNAsync() {
this.$store.dispatch('addNAsync', n);
}
}
触发Actions的第二种方式
可以通过mapActions辅助函数的方式来触发Actions。
// 1. 从vuex中按需导入mapActions函数
import { mapActions } from 'vuex'
...
// 2. 将指定的actions函数,映射为当前组件的methos函数
methods: {
...mapActions(['addAsync', 'addNAsync'),
handleAddAsync() {
this.addAsync();
},
handleAddNAsync(n) {
this.addNAsync(n);
}
}
4 Getters
在Vuex官网中,用到了派生这一词来介绍Getters,在这里可以理解为就是用于对Store中的数据进行加工处理,形成新的数据,类似Vue的计算属性。Getters的数据是基于Store中的数据的,所以当Store中数据发生变化时,Getters中的数据也会随之变化。
定义Getters
例如state中存有todos计划项,其对象有一个done状态表示完成与否。
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
// 这里通过getters定义的doneTodos方法来过滤已完成的todo项
doneTodos: state => {
return state.todos.filter(todo => todo.done);
},
// 这里还可以通过传入getters对象来获取其他方法
doneTodosCount: (state, getters) => {
return getters.doneTools.length;
},
// 传入参数
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id == id);
}
}
})
触发Getters定义函数的第一种方法
this.$store.getters.doneTodos // -> [{id: 1, text: '...', done: true}]
this.$store.getters.doneTodosCount // -> 1
触发Getters定义函数的第二种方法
通过mapGetters来触发Getters中定义的函数
// 1. 导入mapGetters辅助函数
import { mapGetters } from 'vuex'
...
// 2. 将制定的Getters函数映射为当前组件的函数
methods: {
...mapGetters(['doneTodos', 'doneTodosCount']),
handleDoneTodos() {
this.doneTodos();
}
}