你好,我在VueMastery中学习了NuxtJS,我认为他们教的东西真的很好。其中,获取数据的模式包括异步获取,存储和服务。
page / index.vue
<template>
<div></div>
</template>
<script>
export default {
mounted() {
this.$myInjectedFunction("works in mounted");
},
async fetch({ store, app, req, env }) {
await store.dispatch("scooby/getBanners", { page: 1 });
}
};
</script>
store / scooby.js
import ScoobyService from "@/services/ScoobyService.js";
export const state = () => ({
banners: []
});
export const mutations = {
SET_BANNERS(state, banners) {
state.banners = banners;
}
};
export const actions = {
getBanners({ commit }, payload) {
this.$myInjectedFunction("accessible in actions");
const type = payload.type || 1;
const params = `?ad_type=${type}&page=${payload.page}`;
return ScoobyService.adBanner(params).then(response => {
commit("SET_BANNERS", response.data);
});
}
};
services / scoobyService.js
/* eslint-disable no-console */
import { scoobyApiClient, scoobyRequestSetup } from "@/assets/js/axios.js";
const apiModule = "scooby";
const resources = {
adBanner: `/v1/member/banners`
};
export default {
adBanner(getParams) {
// this.$myInjectedFunction("accessible in actions");
const body = {};
const resource = `${resources.adBanner}/${getParams}`;
const [api, req] = scoobyRequestSetup(resource, body, apiModule);
return process.server
? scoobyApiClient.get(api, req)
: scoobyApiClient.post(api, req);
}
};
plugins / combined-inject.js
/* eslint-disable no-console */
export default ({ app }, inject) => {
inject("myInjectedFunction", string => console.log("That was easy!", string));
};
nuxt.config.js
module.exports = {
...
plugins: [
"~/plugins/axios.js"
],
...
}
services / scoobyService.js无法访问this
对象,但store / scooby.js可以访问。如何在services / scoobyService.js
您应该按照以下步骤创建文件,然后可以通过this.$customService
访问服务方法>
services / CustomService.js
您注入的功能仅在有效的Vue实例中可用,而scoobyService.js则不可用(请参阅:Vue instance properties)。您也可以将函数作为导出单独公开,并在服务中使用它。