如何在Vue CDN中使用axios modular API

How to use axios modular API in Vue CDN

我有一个 HTML 并引用了 vue 和 vue-router

现在如果要用axios的话,直接调用路径就可以得到return数据

但我希望能设置文件集中管理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 模块化?

您可以设置 axios's default baseURL 以便所有请求共享相同的 URL 作为其路径的前缀:

axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com/'

我会在 index.html 加载任何会发出 axios 请求的组件之前执行此操作。