2017-09-26 6 views
0

私は現在、私のプロジェクトでvuexを実装しようとしています。状態のプロパティを更新するための突然変異/アクションについて学びました。私は、APIからデータをフェッチすることによって、状態コンポーネントを更新するための最も安全かつ効率的な方法が何であるかを知りたかったのです。たとえば:Vuexを使用してstore.js内のAPI呼び出しを正しく更新してデータを更新するにはどうすればいいですか?

Store.js

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

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

をアクション内のAJAX呼び出しを行い、コールバック内ストアにコミット:私は読むためにeaser側のアクションでコードを作るために、この事を分離することが好きです。 –

答えて

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 }) 
 
);

関連する問題