要在您的 vuex 商店中使用 $http 或 $router,您需要使用主 vue 实例。虽然我不推荐使用这个,但我会在回答实际问题后添加我推荐的内容。
在您的 main.js 或您正在创建 vue 实例的任何地方,例如:
new Vue({
el: '#app',
router,
store,
template: '<App><App/>',
components: {
App
}
})
或类似的东西,您可能还添加了 vue-router 和 vue-resource 插件。
对此稍作修改:
export default new Vue({
el: '#app',
router,
store,
template: '<App><App/>',
components: {
App
}
})
我现在可以像这样在 vuex 商店中导入它:
//vuex store:
import YourVueInstance from 'path/to/main'
checkMovieStore(state) {
const routerMovieId = YourVueInstance.$route.params.movieId;
const storeMovieId = state.movieDetail.movie_id;
if (routerMovieId != storeMovieId) {
let url = "http://dev.site.com/api/movies/movie-list/" + routerMovieId + "/";
YourVueInstance.$http.get(url)
.then((response) => {
state.movieDetail = response.data;
})
.catch((response) => {
console.log(response)
});
}
}
正如Austio 的回答所说,这个方法应该是action,因为mutations 不是为处理异步而设计的。
现在介绍推荐的方法。
-
您的component 可以访问route params 并将其提供给action。
methods: {
...mapActions({
doSomethingPls: ACTION_NAME
}),
getMyData () {
this.doSomethingPls({id: this.$route.params})
}
}
-
action 然后通过抽象的 API 服务文件 (read plugins) 进行调用
[ACTION_NAME]: ({commit}, payload) {
serviceWhichMakesApiCalls.someMethod(method='GET', payload)
.then(data => {
// Do something with data
})
.catch(err => {
// handle the errors
})
}
-
您的actions 执行一些异步工作并将结果提供给mutation。
serviceWhichMakesApiCalls.someMethod(method='GET', payload)
.then(data => {
// Do something with data
commit(SOME_MUTATION, data)
})
.catch(err => {
// handle the errors
})
-
Mutations 应该是唯一修改您的state 的人。
[SOME_MUTATION]: (state, payload) {
state[yourProperty] = payload
}
示例
一个包含端点列表的文件,如果您有不同的部署阶段(具有不同的 api 端点,例如:测试、登台、生产等),您可能需要它。
export const ENDPOINTS = {
TEST: {
URL: 'https://jsonplaceholder.typicode.com/posts/1',
METHOD: 'get'
}
}
以及将Vue.http 实现为服务的主文件:
import Vue from 'vue'
import { ENDPOINTS } from './endpoints/'
import { queryAdder } from './endpoints/helper'
/**
* - ENDPOINTS is an object containing api endpoints for different stages.
* - Use the ENDPOINTS.<NAME>.URL : to get the url for making the requests.
* - Use the ENDPOINTS.<NAME>.METHOD : to get the method for making the requests.
* - A promise is returned BUT all the required processing must happen here,
* the calling component must directly be able to use the 'error' or 'response'.
*/
function transformRequest (ENDPOINT, query, data) {
return (ENDPOINT.METHOD === 'get')
? Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query))
: Vue.http[ENDPOINT.METHOD](queryAdder(ENDPOINT.URL, query), data)
}
function callEndpoint (ENDPOINT, data = null, query = null) {
return new Promise((resolve, reject) => {
transformRequest(ENDPOINT, query, data)
.then(response => { return response.json() })
.then(data => { resolve(data) })
.catch(error => { reject(error) })
})
}
export const APIService = {
test () { return callEndpoint(ENDPOINTS.TEST) },
login (data) { return callEndpoint(ENDPOINTS.LOGIN, data) }
}
queryAdder 以防万一它很重要,我用它来向 url 添加参数。
export function queryAdder (url, params) {
if (params && typeof params === 'object' && !Array.isArray(params)) {
let keys = Object.keys(params)
if (keys.length > 0) {
url += `${url}?`
for (let [key, i] in keys) {
if (keys.length - 1 !== i) {
url += `${url}${key}=${params[key]}&`
} else {
url += `${url}${key}=${params[key]}`
}
}
}
}
return url
}