vue get和post接口请求的使用和操作 |
您所在的位置:网站首页 › vue里面get请求地址怎么拼接 › vue get和post接口请求的使用和操作 |
vue get和post接口请求的使用和操作
vue get和post接口请求的使用和操作axios和qs的安装及引用axios安装qs安装Axios get接口请求Axios get请求有参数的接口Axios post请求post接口请求接口:post 跳转页面传参请求:
vue get和post接口请求的使用和操作
axios和qs的安装及引用
axios安装
npm命令:cnpm install axios --save 引用:在main.js中 import Axios from "axios" //axios接口引用 Vue.prototype.$axios=Axios qs安装npm命令:cnpm install qs 引入(全局引入):在main.js中 import qs from "qs" //qs引用 Vue.prototype.$qs=qs; Axios get接口请求接口请求,首先,在export default中建立生命周期函数created(),在生命周期狗子函数created中适应axios var _this=this; //指定this this.$axios({ //创建接口 methods:'get', //类型为get请求 url:'https://xxxxxxxxx/api/', //请求的接口地址 }) .then(function(response){ //请求成功返回 _this.focus=response.data.focus; //数据打包,打包在data中创建的数组 我这里是focus数组 // console.log(response.data) //打印请求的数据 })完成之后,就可以在控制台看到请求到的数据了, ![在这里插入图片描述](https://img-blog.csdnimg.cn/20191125110357971.png 在export default中建立生命周期函数created() 格式如下: let _this=this //指定this为当前指向 this.$axios({ methods:'get', //请求方式,默认为‘get’ ,可省略 url:'https://xxxxxxxxxxxxxxxxxx', //请求的接口网址 params:{ user_id:7 //user_id为接口请求关键字,7为参数值 } }) .then(function(res){ // console.log(res.data) //请求到的数据打印出来检查有没有出错 _this.list=res.data.adds //将请求到的数据赋值到数组list中 })请求成功后就可以在控制台看到你请求到的接口数据了, 而他的使用,一般都是伴随v-for循环输出接口数据赋值的数组。 Axios post请求post请求跟get请求区别就在于post需要使用qs进行编译转换以便使用,有时候还需要传递参数。 post接口请求接口: let url='https://xxxxxxxxxxxxxxxxxx'; //请求的接口地址 let url_data=this.$qs.stringify({ //使用qs编译转换参数 ,将参数赋值与url_data user_id:7 //qs编译转换的参数, user_id为接口关键字,7为参数值 }) this.$axios.post(url,url_data).then(rese=>{ //post接口请求 this.pri=rese.data.cart //接口数据赋值 console.log(rese.data) //打印接口数据 }) post 跳转页面传参请求:跳转页面传参,就是在跳转的同时把参数传递到跳转后的页面中。 1.跳转:定义一个点击事件,点击之后跳转,同时传参。 例: date是定义的跳转点击事件,com.name是获取的参数 2.然后,编辑这个点击事件:(传递参数使用router) date(id){ //id是方法date带过来的参数 var _this=this; _this.id = id //赋值参数为当前变量id console.log(id) this.$router.push({ //传递参数使用router path:"indexs_seek_deta", //要跳转的页面 query:{ kee:id , //传递的参数 } }) }3.之后,在跳转后的页面接收参数:(接收参数使用route) export default{ data(){ return{ cos:[] //创建接口储存用的数组 } }, created(){ let _this=this var kee_val=this.$route.query.kee //kee为传递过来的参数赋值与kee_val let kdata=this.$qs.stringify({ //使用qs编译转换传递过来的参数传值给 kdata keyword:kee_val //keyword为接口关键字 }) // post接口请求 this.$axios.post('https://xxxxxxxxxxxxxxxxxxx',kdata) .then((res)=>{ console.log(res.data.pro) this.cos=res.data.pro //将接口数据赋于数组cos中 }) } }4.数据的输出:(我这里是v-for循环使用) |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |