1.什么是Vuex?
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据的共享
2.使用vuex统一管理状态的好处
1.能够在vuex中集中管理共享的数据,易于开发和后期维护
2.能够高效实现组件之间的数据共享,提高开发效率
3.存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
3.什么样的数据适合存储到vuex中
一般情况下,只有组件之间的共享数据才有必要存储到vuex中,对于组件中的私有数据,就存储在组件自身的data中
4.vuex的基本使用
1.安装vuex的依赖
npm install vuex --save
2.导入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
3.创建store对象
const store = new Vuex.store({
// state中存放全局共享的数据
state: {count: 0}
})
4.将store对象挂载到vue示例中
new Vue({
el: '#app',
........
store
})
5.vuex的核心概念
5.1 State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中存储
export default new Vuex.Store({
state: {
count: 0
}
})
取出count的方式一
this.$store.state.count
但是值得注意的是在template中可以去掉this
,直接使用$store.state.count
取出count的方式二
//1,引入mapState
(1)import { mapState } from "vuex";
//2,调用mapState
...mapState(["count"]),
//3,在template页面上使用count
{{count}}
5.2 Mutation
Mutation用于变更Store中的数据
1.只能通过Mutation来变更Store中的数据,不可以直接操作Store中的数据
2.这种方式虽然操作起来繁琐了一些,但是可以集中监控所有数据的变化
Mutation更改Store中数据的使用
5.2.1 触发mutations函数的方式一
一:首先在mutations中定义一个函数
export default new Vuex.Store({
state: {
count: 0
},
// 定义Mutation
mutations: {
add(state) {
// 变更状态
state.count++
}
});
___________________________________________________________
//触发Mutation
this.$store.commit('add');
只有Mutation中的函数才有权力修改Mutation中的数据
5.2.2 可以在触发mutations的时候传递参数
mutations: {
addN(state,step) {
// 变更状态
state.count += step;
}
}
//触发mutation
this.$store.commit('addN',3);
5.2.3 触发mutations的第二种方式
1.从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
2. 将指定的mutations函数,映射为当前组件的methods函数
methods: {
...mapMutations(['add','addN']);
}
methods: {
...mapMutations(["sub"]),
btnHandle1() {
this.sub();
}
}
5.2.4 Action用于处理异步任务,触发Action的第一种方式
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据
在mutations中不要使用异步函数
//定义Action
const store = new Vuex.store({
mutations: {
add(state) {
state.count ++;
}
},
actions: {
addAsync(context) {
setTimeout(()=> {
context.commit('add')
},1000)
}
}
})
//触发Action
this.$store.dispath('addAsync');
5.2.5 触发Action的第二种方式
// 1.在actions中定义要触发的mutations
subAsync(context) {
setTimeout(() => {
context.commit('sub');
}, 1000);
}
// 2.按需导入mapActions
import { mapActions } from "vuex";
// 使用
...mapActions(["subAsync"]),
btnHandle2() {
this.subAsync();
},
6. Getter
Getter用于对Store中的数据进行加工处理形成新的数据
1.Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
2.Store中数据发生变化。Getter中的数据也会跟着发生变化
const store = new Vuex.store({
state: {
count: 0
},
getters: {
showNum: state => {
return '当前最新的数据是【' + state.count + '】'
}
}
})
6.1 使用Getters的方式一
this.$store.getters.showNum
6.2 使用Getters的方式二
...mapGetters(["showNum"])