Vue-Axios(Ajax请求)

引入axios文件

下载:

npm install axios

 在script中引入:

import axios from 'axios';//默认暴露所以可以直接引入

或直接引入js

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

发生请求

Get请求

在script中,标明是get请求,地址写在url中,回调参数在then的result.data中

// axios请求
axios({
	method: 'get',
	url: 'http://localhost:8080/sogame/all'
}).then(result => {
	//成功回调,result包含所有数据
	console.log(result.data);//data是接口响应数据
}).catch(err => {
	//失败回调
	console.log("axios请求失败:",err);
});

 可以简化为:

axios.get('http://localhost:8080/sogame/all').then(result => {
	//成功回调,result包含所有数据
	console.log(result.data);//data是接口响应数据
}).catch(err => {});

 携带参数就拼接请求字符串,加上

?id=1&name=z

 或者使用,{params:参数}(这里封装成一个函数,可以给多个vue文件复用)

export async function getAllGamesService(params) {
	//同步等待服务器结果
	return await axios.get('http://localhost:8080/sogame/all')
    .then(result => {
		//成功回调,result包含所有数据
		return result.data;
	}).catch(err => {
	});
}

Post请求

带参传递,数据放在data后

axios({
	method: 'post',
	url: 'http://localhost:8080/sogame/all',
	data:myList
}).then(result => {
	//成功回调,result包含所有数据
	console.log(result.data);//data是接口响应数据
}).catch(err => {
	//失败回调
	console.log("axios请求失败:", err);
});

可以简化为:数据用逗号加在后面

axios.post('http://localhost:8080/sogame/all', myList).then(result => {
	console.log(result.data);//data是接口响应数据
}).catch(err => {});

 展示到页面

可以在script中创建一个变量接收

(这边收到的是一个实例对象的List数组,key最好和接收的key相等)

let gameList = ref([
	{ game_id: '1', game_name: 'title01' }
])

axios.get('http://localhost:8080/sogame/all').then(result => {
		//成功回调,result包含所有数据
		console.log(result.data);//data是接口响应数据
		gameList.value = result.data;
	}).catch(err => {
});

html中循环展示

<ul>
	<li v-for="game in gameList" :key="game.game_id">{{ game.game_name }}</li>
</ul>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值