vuex

vuex官方示意图

整个流程:首先确保是否有异步请求或者异步操作在整个vuex的流程中,如果有就在actions里面进行操作,在操作之前需要发一条消息(this.$store.dispatch(' '))给actions用于接收。接收之后发起请求或者异步操作,然后再commit一条消息给mutations,用于修改state里面的数据(store.commit(' ',data))。

以下是一个完整的栗子。比如在项目中有一个推荐的列表,可以来回的切换,但不需要每次在切换的时候都要去请求一次数据,这样会浪费请求的事件还要多次更新html,所以就利用vuex来完成。
首先在项目下新建一个store文件夹,分别引入vuevuex,以及在vue中注册vuex

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);

接着写入以下内容

const store=new Vuex.Store({
  state:{
    
  },
  actions:{  //在这里处理异步请求(也可以处理同步请求),但是改变状态还是需要在mutations里面进行修改,所以需要commit
    
  },
  mutations:{//在这里处理同步请求,改变state里面的数据,不能异步(比如加定时器)

  }
})
export default store;

然后在main.js中引入并且注册到vue中。

import Vue from 'vue'
import App from './App'
import router from './router'
import store from '../store/index';
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

而我们的项目需要正如上面所说,不需要来回的请求数据,所以我们在页面中就需要这么一段if判断。

if(this.$store.state.recommendList.length===0&&this.$store.state.bannerImg){
  //我们需要判断store里面state的recommendList和bannerImg是否有值,如果没有的话我们就需要dispatch一条消息给actions,告诉actions需要请求。
   this.$store.dispatch('getRecommendList')
}

然后来到store下面的index.js

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);

const store=new Vuex.Store({
  state:{
    recommendList:[],
    bannerImg:[]
  },
  actions:{  //在这里处理异步请求(也可以处理同步请求),但是改变状态还是需要在mutations里面进行修改,所以需要commit
    getRecommendList:function(store){
      axios.get('/v2/page',{
        params:{
          pageId:1,
          tabId:1,
          currentPage:1,
          pageSize:8,
          _:1556056259410
        }
      }).then(res=>{
        let length=res.data.data.modules.length;
        //在actions里面并不能修改state 所以需要commit一条消息给mutations,让mutations里面的函数来修改掉状态。
        store.commit('setRecommendList',res.data.data.modules.slice(1,length))
        store.commit('setRecommendBannerImg',res.data.data.modules[0].moduleContent.banners)
      })
    }
  },
  mutations:{//在这里处理同步请求,改变state里面的数据,不能异步(比如加定时器)
    setRecommendList:function(state,payLoad){
      state.recommendList=payLoad;
    },
    setRecommendBannerImg:function(state,payLoad){
      state.bannerImg=payLoad;
    }
  }
})
export default store;
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 3,051评论 0 7
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 791评论 0 3
  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 8,166评论 4 111
  • 目录 - 1.什么是vuex? - 2.为什么要使用Vuex? - 3.vuex的核心概念?||如何在组件中去使用...
    我跟你蒋阅读 4,243评论 4 51
  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 4,800评论 7 61

友情链接更多精彩内容