我有一个HTML和引用的vue和vue路由器。
现在,如果我想使用axios,我可以通过直接调用路径来获得返回数据。
但是我希望我可以设置文件集中管理apiUrl和apiName并导入它们。
index.html
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/http-vue-loader"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="module" src="/api/server.js"></script>
</head>
<body>
<div id="app">
<p>
<router-link to="/contact">Go to contact</router-link>
</p>
<p>
<router-link to="/about">Go to about</router-link>
</p>
<p>
<router-view></router-view>
</p>
</div>
<head>
<script>
const contact = httpVueLoader('./view/contact.vue')
const about = httpVueLoader('./view/about.vue')
const routes = [
{ path: '/contact', component: contact },
{ path: '/about', component: about }
]
const router = new VueRouter({
routes
})
var app = new Vue({
router,
}).$mount('#app')
</script>
</head>
</body>
</html>
contact.vue
<template>
<p>{{ hello }}</p>
</template>
<script>
module.exports = {
data: function () {
return {
hello: "contact",
};
},
mounted() {
axios
.get('apiUrl/apiName')
.then(response => (console.log(response.data))
.catch(function (error) {
console.log(error);
});
},
};
</script>
<style>
</style>
目前,数据可以通过直接定义的路径获得。我不使用Node.js。可以模块化apiUrl吗?
发布于 2021-03-11 06:57:30
您可以设置axios's default baseURL,以便所有请求共享其路径前缀相同的URL:
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com/'在加载任何生成index.html请求的组件之前,我都会在axios中这样做。
https://stackoverflow.com/questions/66577567
复制相似问题