zoukankan      html  css  js  c++  java
  • vue 将数据保存到vuex中

    在项目中遇到这样一个问题,就是在登入的时候同时需要从后台获取到左边的导航,但是如果使用h5的localStorage来保存导航信息,会出现app加载进去之后localStorage才保存进浏览器,在mounted方法中,console.log(window.localStorage.getItem('xx')打印出来是undefined,于是把数据保存到vuex中管理,以下是把数据保存到vuex中的例子(转载,来源参考https://www.cnblogs.com/jasonwang2y60/p/6606822.html)

    在vue项目中组件间相互传值或者后台获取的数据需要供多个组件使用的情况很多的话,有必要考虑引入vuex来管理这些凌乱的状态,今天这边博文用来记录这一整个的过程,后台api接口是使用webpack-server模拟的接口,这个前面的文章中有提到,需要的可以去翻阅。

    整个的流程是在组件的created中提交dispatch然后通过action调用一个封装好的axios然后再触发nutation来提交状态改变state中的数据,然后在组件的计算属性中获取state的数据并渲染在页面上

    首先新需要在项目中安装vuex:

    运行命令 npm install vuex --save-dev

    在项目的入口js文件main.js中

    import store from './store/index'

    并将store挂载到vue上

    new Vue({
      el: '#app',
      router,
      store,
      template: '<App/>',
      render: (createElement) => createElement(App)
    })

    然后看下整个store的目录结构,modules文件夹用来将不同功能也面的状态分成模块,index.js文件夹是store的入口文件,types文件夹是定义常量mutation的文件夹

    整个vuex的目录结构如下:

    这里我新建了文件夹fetch用来编写所有的axios处理和axios封装

    在fetch文件夹下新建api.js文件:

    import axios from 'axios'
    
    export function fetch(url, params) {
        return new Promise((resolve, reject) => {
            axios.post(url, params)
                .then(response => {
                     alert('Api--ok');
                    resolve(response.data);
                })
                .catch((error) => {
                  console.log(error)
                   reject(error)
                })
        })
    }
    
    export default {
      // 获取我的页面的后台数据
      mineBaseMsgApi() {
         alert('进入api.js')
        return fetch('/api/getBoardList');
      }
    }

    在store的入口文件index.js中:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    import mine from './modules/mine';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      modules: {
        mine
      }
    });

    在你需要请求后台数据并想使用vuex的组件中的created分发第一个dispatch:

    created() {
        this.$store.dispatch('getMineBaseApi');
      }

    然后在store/modules下的对应模块js文件中,这里我使用的mine.js文件中编写state、action和mutation

    import api from './../../fetch/api';
    import * as types from './../types.js';
    
    const state = {
      getMineBaseMsg: {
        errno: 1,
        msg: {}
      }
    }
    
    const actions = {
      getMineBaseApi({commit}) {
        alert('进入action');
        api.mineBaseMsgApi()
        .then(res => {
            alert('action中调用封装后的axios成功');
            console.log('action中调用封装后的axios成功')
            commit(types.GET_BASE_API, res)
        })
      }
    }
    
    const getters = {
      getMineBaseMsg: state => state.getMineBaseMsg
    }
    
    const mutations = {
      [types.GET_BASE_API](state, res) {
        alert('进入mutation');
        state.getMineBaseMsg = { ...state.getMineBaseMsg, msg: res.data.msg }
        alert('进入mutations修改state成功');
      }
    }
    
    export default {
      state,
      actions,
      getters,
      mutations
    }

    然后在想取回state的组件中使用mapGetters获取state:

    import { mapGetters } from 'vuex';
    
    export default {
      ...
      computed: {
        ...mapGetters([
          'getMineBaseMsg'
        ])
      },
      ...      
    }

    然后在控制台查看把:

    getters和mutation都已经成功了,同时我在提交state的整个过程都添加了alert,大家可以看看整个流程是如何走的;

  • 相关阅读:
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
    DS01-线性表
    c博客06-结构体&文件
    C博客作业05--指针
    123
    面向对象设计大作业
    购物车
    有理数类的设计
  • 原文地址:https://www.cnblogs.com/catbrother/p/9386919.html
Copyright © 2011-2022 走看看