vue get和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在这里插入图片描述
然后在里面找到你需要的数据,我这里想要focus中的图片
所以我提取了focus的数据到数组focus中

Axios get请求有参数的接口

在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循环使用)
在这里插入图片描述

  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值