[Vite] 安裝Vue Axios
TL;DR
先前透過cdn以及Vue CLI的方式去載入VeeValidate。這次要在VIte + Create Vue 的環境下安裝Vue Axios這個套件。
參考資料
相關連結
- Vite | Official
- create-vue | Github
- vue-axios | NPM
- random user | 測試用假資料API
安裝vue-axios
npm install --save axios vue-axios
package.json
內容
package.json
內容{
"name": "vite-project",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore",
"format": "prettier --write src/"
},
"dependencies": {
"axios": "^1.6.2",
"pinia": "^2.1.7",
"vue": "^3.3.10",
"vue-axios": "^3.5.2",
"vue-router": "^4.2.5"
},
"devDependencies": {
"@rushstack/eslint-patch": "^1.3.3",
"@vitejs/plugin-vue": "^4.5.1",
"@vue/eslint-config-prettier": "^8.0.0",
"eslint": "^8.49.0",
"eslint-plugin-vue": "^9.17.0",
"prettier": "^3.0.3",
"vite": "^5.0.5"
}
}
調整main.js
src/main.js
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import axios from 'axios'
import VueAxios from 'vue-axios'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(VueAxios, axios)
app.mount('#app')
測試是否載入成功
可以使用Random user來測試是否有正確安裝vue-axios。
到About.vue中,修改如下:
About.vue
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
{{ user }}
</template>
<script>
export default {
data() {
return {
user: {}
}
},
mounted() {
this.$http.get("https://randomuser.me/api/")
.then((response) => {
this.user=response.data.results[0]
console.log(this.user)
})
}
}
</script>
<style>
@media (min-width: 1024px) {
.about {
min-height: 100vh;
display: flex;
align-items: center;
}
}
</style>
透過vue-axios
取得資料