vuex2.0 关于 状态管理state getter mutation 和action

本文深入解析Vue.js状态管理库Vuex的使用方法,包括State的三种获取方式、Getter的计算属性应用、Mutation的state更新机制、Action的异步操作流程及Store的配置整合,为开发者提供全面的Vuex实战指南。

Vuex 状态管理 1 State 三种状态用法

         A.直接获取Store中的State 属性的值
		 
		  Computed:{  // 计算属性
		        Count (){
				   Return This.$Store.State.Count
				}
		  }
		  
		  b.直接从mapState中获取
		  
		     computed:{
			     ...mapState(['count'])      <===>  等同上面的直接获取store中state中的属性值
			 }
			 
		 c.在mapState中定义别名
		      computed:{
			       ...mapState({
				      count:(state) = state.count
				   })
			  }
			  
			  
		以上三种都可以获取当前state中对应的参数值 注意在引用之前我们必须需要引入 
		
		
		import {mapState,mapGetters,mapMutations} from 'vuex'
		
2 getter 获取计算后的state 属性的值 // getter 只是针对的是state里面的参数

        列如 从store的getters中获取到firstNmme 和 lastName 属性 在getter中展示
		
		       fullName (state) {
                  return `${state.firstName}+${state.lastName}`
                }
				
		  computed :{
		     fullName () {
				return this.$store.getters.fullName
			  }
		  }
		  
	    mapGetters 中获取 
		   computed:{
		       ...mapGetters(['fullName'])
		   }
		   
3 mutation 更改state
     updateCount (state,{num}) {
	  state.count = num
 }
	
使用store 的commit 触发mutation 
  mounted (){
  setInterval(()=>{
     this.$store.commit('updateCount',{num:num++})
  },1000)
 }
使用mapMutations 
   methods:{
      ...mapMutations(['updateCount'])
   }
   
   此时ubdateCount的用法 
     mounted(){
	   setInterval (()=>{
	      this.updateCount ({num:num++})
		  
	   },1000)
	 }
	 
	 使用mapMutations 的说法
	     methods:{
		       ...mapMutations(['ubdateCount'])
		 }
4 action异步修改state   
      // action.js
     updateCountAsync (store, data) {
	  setTimeout(() => {
		store.commit('updateCount', {num: data.num})
	  }, data.time)
	}
使用store的dispatch 触发action
  mounted (){
     this.$store.dispatch('updateCountAsync',{num:3,time:2000})
  }
  使用mapActions methods:{
     ...mapActions(['updateCountAsync]);
  }
  此时updateCountAsync的用法
	mounted () {
  this.updateCountAsync({
	num: 3,
	time: 2000
  })
}	  

5 可以直接引入stroe.js 中导入

import Vuex from 'vuex'
import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './action/action'

const isDev = process.env.NODE_ENV === 'development'

export default () => {
  return new Vuex.Store({
	strict: isDev,
	state: defaultState,
	mutations,
	getters,
	actions
  })
}

转载于:https://my.oschina.net/u/3692906/blog/1924425

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值