Vuex数据管理之store使用

Vuex.数据数据存储
1.页面发请求,保存到state中
请求页面:
//对应组件

    async getDataFun(){
    	const res = await reqData()    //接口函数
    	this.centernameData = res.data
    	this.$store.commit('pageDataList',this.centernameData)
    }

store:

	state:{
	  centername:'',
	}
	mutations:{
  pageDataList(state,val){
state.centernameData = val
}
}

接收数据页面:

this.$store.state.centername

2.action发请求,保存数据state
请求页面:

this.$store.dispatch('getDataListAction',{centerName,page,pageSize})

store:

state:{
centername:",
}
    actions:{
    	async getDataListAction({commit},params){
    	  const res = await reqData()    //接口函数
    	  commit('getDataList',res)
    }
    }
    mutations:{
    getDataList(state,res){
    state.centername = res   //处理具体数据改变
    }
    }

3.action发请求,保存大量数据时

store

state:
    	export default:{
		    user:'',
		    }
    index:
        //  vuex核心管理对象store
	       import Vue from 'vue'
		    import Vuex from 'vuex'
		    import state from './state'
		    import mutations from './mutations'
		    import actions from './actions'
		    import getters from './getters'
		    Vue.use(Vuex)
		    export default new Vuex.Store({
		      state,
		      mutations,
		      actions,
		      getters
		    })
	       

     actions:
     
     	        import {  reqUser  } from '../api'
	        import { RECEIVE_USER} from './mutation-types'
	        export default{
	    	//// 同步保存用户的action
	      saveUser ({commit}, user) {
	        commit(RECEIVE_USER, {user})
	      },
	          // 异步获取用户的action
	      async getUser ({commit}) {
	        const result = await reqUser()
	        if(result.code===0) {
	          const user = result.data
	          commit(RECEIVE_USER, {user})
	        }
	      },
	    }
   
   mutations:
   import Vue from 'vue'
	import {RECEIVE_USER} from './mutation-types'
	export default {
		  [RECEIVE_USER] (state, {user}) {
		    state.user = user
		  },
		  
  }

请求页面:

this.$store.dispatch('getUser')

使用数据页面:

<span class="icon-mobile-number">{{user.phone ? user.phone : '暂无绑定手机号'}}</span>
<p class="user-info-top" v-if="!user.phone">{{user.name ? user.name : '登录/注册'}} </p>
 import {mapState} from 'vuex'
 computed: {
      ...mapState(['user'])
    },
  1. 2个引用变量指向同个对象, 通过一个引用变量改变对象内部的数据, 另一个引用变量看到的新的
  2. 2个引用变量指向同个对象, 让一个引用变量指向一个新的对象, 另一个引用变量看到的还是原来的对象

猜你喜欢

转载自blog.csdn.net/diaojw090/article/details/89509601