- A+
所属分类:Web前端
1.首先在cmd中找到你的项目,
然后执行以下命令,安装一下axios
1 cnpm install axios --save //添加axios模块
2 cnpm install qs --save //添加qs模块(用于处理post请求的参数解析)
2.添加成功后,在package.json文件中就可以看到:
1 "dependencies": { 2 "axios": "^0.19.2", 3 "core-js": "^3.6.5", 4 "qs": "^6.9.4", 5 "vue": "^2.6.11", 6 "vue-router": "^3.2.0", 7 "vuex": "^3.4.0" 8 },
3.在main.js文件中导入这些模块
1 import axios from 'axios' 2 import qs from 'qs' 3 //设置axios的基础url部分 4 axios.defaults.baseURL = 'http://api.tianapi.com/'; 5 //将axios挂载到vue实例上,使用时就可以 this.$axios 这样使用了 6 Vue.prototype.$axios = axios; 7 //将qs挂载到vue实例上,使用时就可以 this.$qs 这样使用了 8 Vue.prototype.$qs = qs;
4.Vue中axios的三种使用方法
1 Vue.axios.get(api).then((response) => { 2 console.log(response.data) 3 }) 4 5 this.axios.get(api).then((response) => { 6 console.log(response.data) 7 }) 8 9 this.$http.get(api).then((response) => { 10 console.log(response.data) 11 })
5.在.vue文件中书写代码(1)
<template> <div class="about"> <h1>全国省市疫情</h1> <table> <tr> <th>省市</th> <th>累计确诊</th> <th>累计治愈</th> <th>现有确诊</th> <th>累计死亡</th> </tr> <tr v-for="item in yq.newslist"> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> </div> </template> <script> export default{ name:'About', data(){ return { yq:{} } }, created() { /* //get方式 this.$axios.get('txapi/ncovcity/index',{ params:{ key:'自己的key' } }).then(function(response) { console.log(response.data); }).catch(function(error) { console.log(error); }); */ //post方式 this.$axios.post('txapi/ncovcity/index',this.$qs.stringify({ key:'e0a32a8ea4275e9dbe2628d03bb91f3e' })).then((response)=> { this.yq = response.data; console.log(this.yq); }).catch((error)=> { console.log(error); }); } } </script> <style scoped> table { width: 100%; text-align: center; border-bottom: solid 2px #DDD; /* 合并边框 */ border-collapse: collapse; } td,th { border-bottom: solid 1px #DDD; height: 40px; } </style>
(2)
1 <template> 2 <div> 3 <el-table :data="news"> 4 <el-table-column prop="id" label="id"></el-table-column> 5 6 <el-table-column prop="name" label="name"></el-table-column> 7 8 <el-table-column prop="psw" label="psw"></el-table-column> 9 </el-table> 10 </div> 11 </template> 12 13 <script> 14 export default { 15 data() { 16 return { 17 18 news:[] 19 } 20 }, 21 created(){ 22 let than=this 23 this.$axios({ 24 methon:'post', 25 url:'http://localhost:8888/pro0727/hello' 26 }).then(function(response){ 27 console.log(response); 28 than.news=response.data 29 }) 30 } 31 } 32 </script> 33 34 <style> 35 </style>