vue动态数据获取swiper轮播图的宽高,即@load的应用

vue开发中轮播图是一个非常常见的效果,那么在页面中我们要如何知道一个图片的宽高呢?

开始之前你们是否知道onload这样一个事件?

onload 事件在图片加载完成后立即执行。

同样的在vue图片中也有这么一个事件,即@load

@load触发须知

1、image src有值的时候,才开始加载

2、onload事件是在src的资源加载完毕的时候,才会触发

完整代码:

<template>
<div style="">
<swiper ref="mySwiper" :options="swiperOptions" :style="{ height: bannerHeight + 'px' }">
<swiper-slide v-for="(item,index) in bannerList" :key="index">
<a href="javascript:void(0)" target="_blank">
<img ref="img" :src="item.url" width="100%" alt="" @load="loadImage">
</a>
</swiper-slide>
</swiper>
</div>
</template>

<script>
import {
Swiper,
SwiperSlide,
directive
} from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
import {
getBanner
} from '@/api/api_index.js'
export default {
name: 'HelloWorld',
components: {
Swiper,
SwiperSlide
},
directives: {
swiper: directive
},
props: {
},
data () {
return {
swiperOptions: {
// direction: 'vertical',
// autoHeight: true,
// autoplay: true,
delay:5000,
loop: true,
// pagination: {
// el: '.swiper-pagination'
// },
// Some Swiper option/callback...
},
bannerHeight:0,
bannerList:''
}
},
computed: {
swiper () {
return this.$refs.mySwiper.$swiper
}
},
created() {
let _this = this
getBanner({}).then(res => {
_this.bannerList = res.result
console.log("BANNER:", _this.bannerList)
}).catch(err => {});
},
methods:{
loadImage:function(){
this.bannerHeight = this.$refs.img[0].height
}
},
mounted(){
}
}
</script>

<style scoped lang="less">

</style>

实现原理解析:

1、通过getBanner获取到图片数据并更新到img的src路径中

2、对img标签绑定@load事件,即当图片加载完成后就执行@load中的方法

3、通过this.$refs.img[0].height获取img数组中的第一个图片的宽高。

注:因为这里所有图片宽高比例都是相同的,所以只获取了第一个数据的宽高即可,如果你宽高比例不同,可以通过循环img来获取每一个图片的宽高设置。

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!