cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
注:使用 CDN 链接就可以不需要去下载对应的 js 文件到本地,只需要联网即可使用,可以减少项目的体积
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Axios</title>
</head>
<body><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>const result = axios({method: 'GET',url: 'http://www.liulongbin.top:3006/api/getbooks'})then(function(books){console.log(books)})</script>
</body>
</html>
<body><button id="btnGet">get</button><button id="btnPost">post</button><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>document.querySelector('#btnGet').addEventListener('click',async function(){const { data:res} = await axios.get('http://www.liulongbin.top:3006/api/getbooks',{params: {id: 1}})console.log(res)})document.querySelector('#btnPost').addEventListener('click',async function(){const { data:res} = await axios.post('http://www.liulongbin.top:3006/api/post',{name: 'zs',gender: '女'})console.log(res)})</script>
</body>
import axios from 'axios'// Vue.prototype.axios = axios
Vue.prototype.$http = axios
如果每次使用都要导入一次,那就太麻烦了,也降低了可维护性
可以在 main.js 文件中导入 axios ,这样就不需要在每个组件中都重新导入了
methods: {async postInfo() {const { data: res } = await this.$http.post('http://www.liulongbin.top:3006/api/post', { name: 'zs', age: 20 })console.log(res)}
}
// 全局配置 axios 的请求跟路径
axios.defaults.baseURL = 'http://www.liulongbin.top:3006'
缺点:不利于 API 的复用!
一 叶 知 秋,奥 妙 玄 心