vuex基本使用
实现组件间数据共享的方案
有什么好处?
①集中管理数据易于开发和维护
②提高开发数据
③实时保持数据自动同步
其中共有的数据才有必要保存在vue中
安装使用
安装:npm install vuex --save
导入vuex包:import Vuex from ‘vuex’
安装到vue上:vue.use(vuex)
创建sotre对象:
const store=new Vuex.store({
state:{},
mutations:{},
actions:{},
getters:{}
})
将store对象挂载到vue中(main.js文件):
new Vue({
store
})
state
state:保存共享数据源
访问state的数据:
①直接使用this.$store.state.全局数据名称
②按需在需要使用的组件内引入mapstate函数
import {maostate} from ‘vuex’
通过mapstate函数将当前组件需要的全局函数映射为当前组建的computed计算属性
computed:{
…mapstate([‘count’])//其中…是mapstate函数调用后映射成当前组件的计算属性
}
mutation
变更store中state的数据(即操作state中的数据)
其中定义函数,函数中state.变量进行操作
mutations:{
add(state,step){
state.count++
}
}
调用mutation中的这个函数:
①使用this.$store.commit(‘add’,value)//add是事件名称,value是传递的参数,当没有参数时可以不写
②在组件内调用函数,先引入mapmutation
import {mapmutation} from 'vuex
映射成组件的methods
methods:{
…mapmutation([‘sub’])
}
就可以直接在组件内使用函数了
但是需要注意一点,mutation中不能写异步代码,只能写同步代码。
action
处理异步任务,在action中不能直接修改state中的数据,必须通过mutation中的函数修改=====》通过commit(’’)触发函数
即:在action中写出如下函数事件
actions:{
addsync(context){
context.commit(‘add’)
}
}
触发异步函数的方法:
①this.$store.dispatch(‘addsync’)
②导入mapactions函数
import {mapactions} from ‘vuex’
在组建的methods中映射成当前组件的方法
mrthods:{
…mapactions([‘addsync’])
}
getter
对store中的数据进行加工处理,不改变原数,类似于computed
定义:store中的getters:{ }
getters:{
showNumber:state=>return ‘当前最行数量+state.count’
}
触发函数的方式:
①this.$store.getters.名称
②导入maofetters
import {mapfetters} from ‘vuex’
在methods中映射成当前组件的方法
methods:{
…maofetters([‘名称’])
}