vuex
1.vuex概述
1.2 vuex是什么
vuex是实现组件全局状态管理的一种机制,可以方便的实现组件之间的数据的共享
1.3 使用vuex统一管理状态的好处
1)能够在vue中集中管理共享的数据,易于开发和后期维护
2)能够高效的实现组件之间的数据共享,提高开发的效率
3)存储在vuex中的数据都是响应式的,能够实现保持数据与页面同步
1.4 什么样的数据适合存储到Vuex中
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中,对于组件中的私有数据,依旧存储在组件自身的data中即可
2.vuex的基本使用
2.1 vuex的安装步骤
1)安装vuex依赖包
> npm install vuex --save
2)导入vuex包(store里面的index.js)
import Vuex from ‘vuex’
Vue.use(Vuex)
3)创建store对象 (store里面的index.js)
const store = new Vuex.store({state:{count:0}})
4)将store对象挂载到vue实例中(main.js)
new vue({el:‘#app’,
render:h->h(app),
router,
store
})
3.Vuex的核心概念
3.1 核心概念概述
vuex中的主要核心概念如下:
State,Mutation,Action,Getter
State
她是提供唯一的公共数据,所有的数据都要统一的放到store的state中进行存储
const store =new Vuex.store({
state:{count:0}
})
组件访问State中数据的第一种方式
this.$store.state.全局数据名称(count)
组件访问State中数据的第二种方式( //…为展开运算符,表示把count映射到这里面)
import { mapState } from “vuex”
computed:{
…mapState([‘count’])
}
Mutation
她是用于变更store中的数据
1)只能通过他来变更store数据,不可以直接操作store中的数据
2)通过这种方式虽然操作起来优点繁琐,但是可以集中控制所有的数据的变化
const store =new Vuex.store({
state:{count:0},
mutations:{
//参数永远是state这个对象
add(state){
state.count++
}
}
})//触发mutations commit就是要调用store里面的某个方法
methons:{
handle(){
this.$store.commit(‘add’)
}
}
3)可以在触发他的时候传递参数
const store =new Vuex.store({
state:{count:0},
mutations:{
//参数永远是state这个对象
add(state,step){
state.count+=step
}
}
})//触发mutations
methons:{
handle(){
this.$store.commit(‘add’,3)
}
}
组件访问State中数据的第二种方式
import { mapMutations } from “vuex”
methods:{
…mapMutations([‘add’,‘addn’])
fangfa(){
this.add()
this.add(参数)
}
}
带参数和刚刚的方法一样
注意:不要在mutations里面写异步的操作
Action
action用于处理异步任务
如果通过异步操作变更数据,必须通过action,而不能使用mutation,但是在action中还是要通过触发mutation的方式间接变更数据 下面的context可以理解为new Vuex.store(
const store =new Vuex.store({
state:{count:0},
mutations:{
//参数永远是state这个对象
add(state,step){
state.count+=step
}
},
actions:{
addAsync(context){
setTimeout(()=>{
context.commit(‘add’)
},1000)
}
}
})
//触发Action
methods:{
handle(){
this.$store.dispatch( addAsync)
}
}
带参数和刚刚的方法一样
触发的第二种方式
import { mapAction } from “vuex”
methods:{
…mapAction([‘addASync’,‘addasyncto’])
}
addASync可以直接在这个页面用@click=“addASync” ,因为映射过来就相当于把那个函数拿到本页面了
Getter
Getter用于Store中数据进行加工处理形成新的数据(他不会修改store里面的原数据)
1)Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
2)Store中数据发生变化,Getter的数据也会跟着变化
//定义Getter
const store=new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state=>{
return ‘当前最新的数量是【‘+state。count+’】’
}
}
})
使用Getters的第一种方式
this.$store.getter.名称
第二种方式
import { mapGetters } from “vuex”
methods:{
…mapGetters([‘addASync’])
}