我最近已将axios添加到名为services.js
的文件中,因此井井有条。该文件在我的根文件夹中。
@ / services.js
import axios from "axios";
const axiosInstance = axios.create({
baseURL: " server url here",
});
export const api = {
get(endpoint) {
return axiosInstance.get(endpoint);
},
post(endpoint, body) {
return axiosInstance.post(endpoint, body);
},
};
然后,我的视图文件夹中有一个名为Post.vue
的组件:
<template>
<section>
<div>
<ul></ul>
</div>
</section>
</template>
<script>
import { api } from "@/services.js";
export default {
name: "Post",
props: ["id"],
data() {
return {
post: null,
};
},
methods: {
getPost() {
api.get(`/post/${this.id}`).then(response => {
this.post = response.data;
console.log(this.post);
});
},
},
created() {
this.getPost();
},
};
</script>
<style></style>
我还有一个包含所有路由的router.ts文件:
import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import Home from "../views/Home.vue";
import Podcasts from "../views/Podcasts.vue";
import Post from "../views/Post.vue";
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{
path: "/",
name: "home",
component: Home,
},
{
path: "/podcasts",
name: "podcasts",
component: Podcasts,
},
{
path: "/post/:id",
name: "post",
component: Post,
props: true,
},
],
});
export default router;
这给了我一个依赖错误,例如@ / services.js不存在。
不确定当前阶段出了什么问题。
非常感谢您的帮助
答案 0 :(得分:1)
检查您的webpack配置,具体取决于您拥有的webpack的版本,应该有这样的别名@
:
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
"@": path.resolve(__dirname) // check the path here
}
}
};
或者如果您使用的是vue.config.js
configureWebpack: {
name: name,
resolve: {
alias: {
'@': path.resolve(__dirname)// check the path here
}
}
},
确保正确设置了路径。您提到您还有另一个可以正常运行的项目,这使其成为一个很好的参考。
答案 1 :(得分:1)
在标准Vue CLI项目中,@
符号解析为/src
如果您的文件位于项目的根目录中,请尝试
import { api } from '@/../services'
但就我个人而言,我将其移至src
您可以check the Webpack configuration使用
vue inspect