一篇搞定Vuex(含代码示例)

vue通信总结

父对子:v-bind

子对父:v-on

兄弟组件之间:EventBus

$on 接收数据的那个组件

$emit 发送数据的那个组件

Vuex是实现组件全局状态管理的一种机制,可以方便的实现组件数据共享。

使用全局store管理

Vuex 统一状态管理

数据集中管理,易于开发和后期维护

高效实现数据共享,提高开发效率

存储vuex中的数据是响应式的,能够实时保持数据与页面的同步

Vuex基础使用

构建store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
		count: 0
    }, //唯一公共数据源,定义全局共享数据
       //访问:this.$store.state.count
    mutations: {
		add(state){
			state.count++
		}
    },//用于变更store数据,使用其的变更行为可被集中监控
    actions: {
        
    }
})

引入store.js

...
import store from './store'
...
 
...

new Vue({
  ...
  store,
  ...
}).$mount('#app')  

state => 数据使用

直接使用
this.$store.state.count
mapState

也可按需导入mapState函数,将全局数据映射为当前组件计算属性

import { mapState } from 'vuex'
computed: {
	...mapstate(['count'])
}

mutation => 数据更改

触发

在mutation中定义函数后,触发mutation

methods: {
	handle1(){
		this.$store.commit('add')
	}
}
带参数触发
    mutations: {
		addN(state,step){
			state.count+=step
		}
    }
methods: {
	handle1(){
		this.$store.commit('addN',3)
	}
}
mapMutations

按需引入mutation并映射为methods

import { mapMutations } from 'vuex'
methods: {
	...mapMutations(['add','addN'])
}

注:

mutation中不能写入异步代码,否则vue调试器不能正常工作

action => 处理异步

用于处理异步操作

action通过commit触发mutation的方式间接变更数据

定义action
actions: {
	addAsync(context){
		setTimeout(()=>{
			context.commit('add')
		},1000)
	}
}
触发action
methods: {
	handle(){
		this.$store.dispatch('addAsync')
	}
}
带参数的action

定义对应的mutation时即定义为带参数的

定义actions时定义带参数的

使用action时传入参数

actions: {
	addAsync(context,step){
		setTimeout(()=>{
			context.commit('add',step)
		},1000)
	}
}
methods: {
	handle(){
		this.$store.dispatch('addAsync',5)
	}
}
mapActions
import { mapActions } from 'vuex'
methods: {
	...mapActions(['addAsync'])
}

getter

getter不会修改数据

类似于computer

自动响应store中的数据变化

定义getter
getters: {
	showNum: state => {
		return '当前最新的数量是'+state.count
	}
}
触发getter
this.$store.getters.showNum
mapGetters
import { mapGetters } from 'vuex'
computed: {
	...mapGetterss(['showNum'])
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值