如何使用Vuex更新数据在store.js中正确进行API调用?

时间:2017-09-26 22:20:54

标签: javascript vue.js vuejs2 vuex

我目前正在尝试在我的项目中实现vuex。我已经了解了更新状态属性的突变/动作。我想知道通过从API获取数据来更新状态组件的最安全有​​效的方法。例如:

Store.js

export default {
    state {
        prop1:'',
        prop2:''
    }

    actions {
        //how to call API here and update the prop1 and prop2 value
    }
}

1 个答案:

答案 0 :(得分:0)

从我的真实项目中查看这个商店。我已发表评论,向您解释代码的某些部分:



import {
  PAGES_FIND,
  PAGES_FIND_ERROR,
  PAGES_FIND_SUCCESS,
} from '../mutation-types';
import { PagesAPI } from '../../api';

const state = {
  loading: false, // this is needed to show `loading` screen
  error: null,    // this is needed to store and show error to the user (API errors)
  pages: [],      // pages will be here after fetching
};

const mutations = {
  [PAGES_FIND](state) {
    state.loading = true;
  },
  [PAGES_FIND_SUCCESS](state, payload) {
    state.loading = false;
    state.error = null;
    state.pages = payload;
  },
  [PAGES_FIND_ERROR](state, payload) {
    state.loading = false;
    state.error = payload;
  },
};

const getters = {};
/**
 * All AJAX calls should be here. I prefer to use `axios` for this job. 
 * I will show you PageAPI later
 */
const actions = {
  /**
   * Fetches list of pages. Returns all the pages by default
   * @param {Function} [commit] - Commit function
   * @param {Object} [params={}] - Fetch params (it may be filter, limit, etc)
   * @returns {Promise}
   */
  fetchPages({ commit }, params = {}) {
    commit(PAGES_FIND); // we need to show 'Loading...' inside the component
    return PagesAPI.find(params)
      .then(res => commit(PAGES_FIND_SUCCESS, res.data))
      .catch(err => commit(PAGES_FIND_ERROR, err));
  },
};

const namespaced = true;

export default {
  state,
  getters,
  mutations,
  actions,
  namespaced,
};




PageAPI实施就在这里。我喜欢将这些内容分开,以使旁边的代码更易于阅读:



/* eslint-disable import/prefer-default-export */
import axios from 'axios';
import config from '../../config';

const ENDPOINT = `${config.service.baseUrl}/pages`;

/**
 * Returns pages
 * @param {Object} params
 */
export const find = params => (
  axios.get(ENDPOINT, { params })
);