Home > Software design >  How to add Axios package to non-CLI Vue 3 project
How to add Axios package to non-CLI Vue 3 project

Time:12-23

I am attempting to add the Axios package to my non-CLI Vue 3 project. I attempted to add the package in the script tags at the top of the page, but that did not work. I also tried creating a new variable for axios while directly passing the axios package URL to the variable, but that also did not work. How can I go about setting up the Axios package in my project?

Here is the code below:

<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.tailwindcss.com"></script>

<div id="demo" >
<!-- UI -->
</div>

<script>
    const { axios } = "https://unpkg.com/axios/dist/axios.min.js";
    const { onMounted, ref, computed } = Vue
    const app = Vue.createApp({

    const cities = ref()
    
    setup() {
     const getData = async (e) => {
              if (e.key == "Enter") {
              try {
                  const res = await axios.get(
                    `https://api.openweathermap.org/data/2.5/weather?zip={enterzipcodehere},US&appid={youropenweathermapidhere}&units=imperial`
                  )
                  cities.value = res.data.name
                  
                  console.log(cities.value)
                } catch (error) {
                  console.log(error)
                }
              }
        }

     onMounted(() => {
       getData()
     }
    }
})
app.mount('#demo')
</script>

CodePudding user response:

From the installation documentation...

Using jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Using unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

After you add either of those tags to your HTML page, the axios global variable will be available.


Alternately, you can import the ESM version if you use a module

<script type="module">
import axios from "https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.2/esm/axios.min.js";

console.log(
  "todo:",
  (await axios.get("https://jsonplaceholder.typicode.com/todos/1")).data
);
</script>

CodePudding user response:

Add <script src="https://unpkg.com/axios/dist/axios.min.js"></script> in html, and you can use axios as a blobal variable directly.

  • Related