【问题标题】:How to use axios modular API in Vue CDN如何在 Vue CDN 中使用 axios 模块化 API
【发布时间】:2021-06-09 03:40:00
【问题描述】:

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

现在如果我要使用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可以模块化吗?

【问题讨论】:

    标签: vue.js axios vue-router


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 2021-04-03
      • 2020-03-11
      • 2021-12-10
      • 2021-07-27
      • 2018-04-25
      • 2019-02-02
      • 2018-07-23
      • 2021-06-08
      相关资源
      最近更新 更多