Vue从接口请求数据

本文介绍如何使用Vue.js和vue-resource加载并展示图片列表。通过HTTP GET请求从服务器获取图片URL列表,并将其显示在一个动态生成的图片列表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!doctype html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>获取图片列表</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />	 	
	</head>
	<body>
		<div id="app">
			<ul>
				<li>
					<img v-for="imgItem in imgList" v-bind:src="imgItem.img" alt="" width="100%" height="100%"/>
				</li>
			</ul>
		</div>		
	</body>
	<script src="//cdn.bootcss.com/vue/2.1.0/vue.js" type="text/javascript" charset="utf-8"></script>
    <script src="//cdn.bootcss.com/vue-resource/1.0.3/vue-resource.js" type="text/javascript" charset="utf-8"></script>
    <script>
		var demo=new Vue({
			el:'#app',
			data: {
				imgList:[],
				getImgUrl: ''    //存数据接口				
			},
			created: function(){
				this.getImg()              //定义方法
			},
			methods: {
				getImg: function(){
					var that = this;       
					that.$http({           //调用接口
						method:'GET',
						url:this.getImgUrl  //this指data
					}).then(function(response){  //接口返回数据
						this.imgList=response.data;							
					},function(error){
					})
				}
			}
		})
	</script>
</html>

  

转载于:https://www.cnblogs.com/kymming/p/6484626.html

Vue.js 开发中,如果你想要中断正在进行的 API 接口请求,通常会通过 Vue 的生命周期钩子、Vuex 状态管理库或者 Axios 库来处理。以下是几种常见的方式: 1. **Vue 生命周期钩子**: - 在 `beforeDestroy` 或者 `asyncData`(如果在组件中使用)中,你可以取消之前发起的请求。例如,如果你使用的是 axios: ```javascript data() { return { loading: false, data: null } }, mounted() { this.fetchData().catch(() => { /* 请求失败时取消 */ }); }, beforeDestroy() { // 取消正在请求数据 if (this.$axios.isCancel(this.cancelToken)) return; this.cancelToken && this.cancelToken.unsubscribe(); }, methods: { fetchData() { this.loading = true; const cancelTokenSource = axios.CancelToken.source(); this.cancelToken = cancelTokenSource.token; return axios.get('/api/data', { cancelToken: cancelTokenSource.token }).then(response => { this.data = response.data; this.loading = false; }) .catch((error) => { if (axios.isCancel(error)) { console.log('Request cancelled'); } else { console.error(error); } }); } } ``` 2. **Vuex**: 如果你在 Vuex store 中管理数据请求状态,可以创建一个异步 action 并使用 `cancelToken` 来控制请求。当组件销毁时,通过 dispatch 一个取消请求的操作。 3. **Axios插件**: 有些开发者可能会选择使用第三方的 Axios 插件如 vue-axios 或 vaxios,它们通常内置了取消请求的功能,只需要在需要的地方引用并取消请求即可。 记得在每个具体的场景下,检查官方文档或所使用的库是否有提供相应的取消请求函数或方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值