1. 快速使用
- npm install axios
- LoginView.vue
import axios from "axios" axios.get("...") axios.post("...") axios.axios({method: "get" })
2. 通用配置
- npm install axios
- plugins/axios.js
import axios from "axios";let config = {baseURL: "xxx",timeout: 20 * 1000 // ms }const _axios = axios.create(config) // 拦截器 _axios.interceptors.request.use(function (config){xxx;return config })export default _axios
- LoginView.vue
<script setup> import _axios from "@/plugins/axios.js"; _axios.get("/api/v1/course/category/free/?courseType=free").then((res) => {console.log(res.data) }) </script>
3. 示例
plugins/axios.js
import axios from "axios";let config = {baseURL: "https://api.luffycity.com/",timeout: 20 * 1000
}const _axios = axios.create(config)// 拦截器
_axios.interceptors.request.use(function (config){// console.log("请求前:", config)// 1. 去pinia中读取当前用户token// 2. 发送请求时携带tokenif(config.params){config.params["token"] = "djbfkjbdfkj"} else {config.params = {"token": "whejsabjdnfj"}}return config
})export default _axios
LoginView.vue
<template><div class="box"><p>用户名:<input type="text" placeholder="用户名" v-model="msg.username"></p><p>密码:<input type="text" placeholder="密码" v-model="msg.password"></p><p><button @click="doLogin">登录</button></p></div>
</template><script setup>
import {ref} from "vue";
import {useRouter} from "vue-router";
import {userInfoStore} from "@/stores/user.js";
import _axios from "@/plugins/axios.js";const msg = ref({username: "",password: ""
})
const router = useRouter()
const store = userInfoStore()const doLogin = function () {// 1、获取数据console.log(msg.value)// 2、发送网络请求_axios.get("/api/v1/course/category/free/?courseType=free").then((res) => {console.log(res.data)})// 3、本地存储用户信息(登录凭证)// localStorage.setItem("name", msg.value.username)let info = {id: 1, name: msg.value.username, token: "ddsafhsjdfkj"}store.doLogin(info)// 3、跳转到首页router.push({name: "mine"})
}</script><style scoped>
.box {width: 300px;margin: 100px auto;
}
</style>