vue+vuex+axios從後臺獲取數據存入vuex,組件之間共享數據
在vue項目中組件間相互傳值或者後臺獲取的數據須要供多個組件使用的狀況不少的話,有必要考慮引入vuex來管理這些凌亂的狀態,今天這邊博文用來記錄這一整個的過程,後臺api接口是使用webpack-server模擬的接口,這個前面的文章中有提到,須要的能夠去翻閱。javascript
整個的流程是在組件的created中提交dispatch,而後經過action調用一個封裝好的axios而後再觸發mutation來提交狀態改變state中的數據,而後在組件的計算屬性中獲取state的數據並渲染在頁面上css
首先新須要在項目中安裝vuex:html
運行命令 npm install vuex --save-dev前端
在項目的入口js文件main.js中vue
import store from './store/index'html5
並將store掛載到vue上java
new Vue({ el: '#app', router, store, template: '<App/>', render: (createElement) => createElement(App) })
而後看下整個store的目錄結構,modules文件夾用來將不一樣功能也面的狀態分紅模塊,index.js文件夾是store的入口文件,types文件夾是定義常量mutation的文件夾node
整個vuex的目錄結構以下:webpack
這裏我新建了文件夾fetch用來編寫全部的axios處理和axios封裝ios
在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' ]) }, ... }
而後在控制檯查看把:
getter和mutation都已經成功了,同時我在提交state的整個過程都添加了alert,你們能夠看看整個流程是如何走的;