Vuex是什么
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享使用Vuex统一管理数据的好处
① 能够在Vuex中集中管理共享的数据,易于开发和后期维护②能够高效的实现组件之间的数据共享,提高开发效率
③储存在Vuex中的数据都是响应式的,能够实时保持数据与页面的同步
什么样的数据适合存储到Vuex中
一般情况下,只有组件之间共享的数据,才有必要存储到Vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可使用方法
首先安装vuex依赖包
然后在src文件夹内创建一个名为store.js的文件
文件的内容
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
}
})
然后main.js要导入store,render函数中要挂载store
//main.js
import store from './store'
new Vue({
store,
router,
render: h => h(App)
}).$mount('#app')
完成导入
核心概念概述
Vuex中的核心概念如下State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储//创建Store数据源,提供唯一公共数据
const store=new Vuex.Store({
state:{
count:0 //这个count就是共享的数据
}
})
组件中访问State中数据的第一种方式:
this.$store.state.全局数据名称
在< template>不用写this.
组件中访问State中数据的第二种方式:
//1.从Vuex中按需导入mapState函数
import {mapState} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
//2.将全局数据,映射为当前组件的计算属性
computed:{
..mapState(['count'])
}
Mutation
Mutation用于变更Store中的数据①只能通过Mutation变更Store数据,不可以直接操作Store中的数据
②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
//定义Mutation
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state){
//变更状态
state.count++
}
}
})
//触发mutation
methods:{
handlel(){
//触发mutations的第一种方式
this.$store.commit('add')
}
}
如何传递参数
//定义Mutation
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state,step){
//变更状态
state.count+=step
}
}
})
//触发mutation
methods:{
handlel(){
//触发mutations的第一种方式
this.$store.commit('add',3) //携带了参数
}
}
Action
Action用于处理异步任务如果通过异步操作变更数据,必须通过Action,而不能通过Mutation,但是再Action中还是要通过触发Mutation的方式间接变更数据
//定义Action
const store = new Vuex.Store({
mutations:{
add(state){
state.count++
}
}
actions:{
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
}
}
})
//触发Action
methods:{
handle(){
this.$store.dispatch('addAsync')
}
}
Getter
Getter用于对Store中的数据进行加工形成新的数据。①Getter可以对Store中已有的数据加工处理后形成新的数据,类似Vue的计算属性。
②Store中数据发生变化,Getter的数据也跟着发生变化
//定义Getter
const store = new Vuex.store({
state:{
count:0
},
getters:{
showNum:state=>{
return '当前最新的数量是【'+state.count+'】'
}
}
})
使用Gettert
this.$store.getters.变量名