In a VUE project, there are many cases in which values are transmitted between components or data acquired in the background needs to be used by multiple components, so it is necessary to consider introducing VUEX to manage these messy states. Today’s blog post is used to record the whole process. The background API interface is simulated by Webpack-Server. The article in front of this has mentioned, need can go browsing. The whole process is to commit the Dispatch in the component’s Created, then invoke an encapsulated AXIOS via action and trigger mutation to commit the data in the state-changed state, then fetch the state data in the component’s calculated properties and render it on the page
First you need to install vuex in your project: Npminstallvuex –save-dev import store from ‘./store/index’ and mount store to vue new vue ({el: ‘#app’, router, store, template: ”, render: (createElement) => createElement(App)}) Here I create a new folder called FETCH to write all the AXIOS processing and AXIOS wrapping
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)
})
})
}
Return fetch(‘/ API /getBoardList’); return fetch(‘/ API /getBoardList’); return fetch(‘/ API /getBoardList’); }} in store entry file 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 } }); Created () {this.$store.dispatch(‘getMineBaseApi’); } state, action, and mutation import API from ‘./.. /.. /fetch/api’; import * as types from ‘./.. /types.js’;
const state = {
getMineBaseMsg: {
errno: 1,
msg: {}
}
}
Const Actions = {getMineBaseApi({commit}) {alert(‘ enter action’); Api.minebasemsgapi ().then(res => {alert(‘action calls wrapped AXIos successfully ‘); Console. log(‘ wrapped AXIos was successfully called in action ‘) commit(types.get_base_API, res)})}}
const getters = {
getMineBaseMsg: state => state.getMineBaseMsg
}
Const mutations = {types.GET_BASE_API {alert(‘ enter mutation’); state.getMineBaseMsg = { … Status, MSG: res.data. MSG} alert(‘ open mutations ‘); }}
Export default {state, actions, getters, mutations} then use mapGetters in the component that you want to fetch state: import { mapGetters } from ‘vuex’;
Export default {… computed: { … MapGetters ([‘getMineBaseMsg’])},… } then view it in the console:
Getter and mutation have been successful, and I added alert throughout the state submission process. You can see how the whole process works.