vue element-plus 走马灯的实现

实现点击图片可以访问外部链接

先说说自己遇到的问题

linkTo () {
            let activeIndex = this.$refs.carousel.activeIndex
            window.open(this.imgs[activeIndex].link,"_blank")
        }

按道理这样添加点击事件就大功告成了。

这里用到了Carousel组件

但是我执行之后提示link未定义 就是找不到imgs的当前的下标,定位不到当前图片所在imgs,这样就找不到link的超链接了。

研究了很久发现initialIndex是好使的,可以定位到第一张图片的下标,但activeIndex死活没用......

于是我改用传值+判断的方式解决了。但我还是不知道为什么activeIndex不能使用,main.js也是配置好的。

activeIndex:用来标识当前页的一个属性。

initialIndex:用来标识第一页的一个属性。

上代码:

<template>
  <el-carousel :interval="3000" type="card" height="250px" ref="carousel" >
    <el-carousel-item v-for="item in imgs" :key="item.url" name="index"  @click.native="linkTo(item.id)">
      <img :src="item.url"/>
    </el-carousel-item>
  </el-carousel>
</template>
<script>
export default {
  methods: {
    linkTo (i) {
      switch (i){
        case 0:window.open(this.imgs[this.$refs.carousel.initialIndex].link,"_blank");break
        case 1:window.open(this.imgs[this.$refs.carousel.initialIndex+1].link,"_blank");break
        default:break
      }
    },
    //下面是自适应框体大小的设置
    setSize:function () {
      // 通过浏览器宽度(图片宽度)实现计算高度
      this.bannerHeight = 400 / 1920 * this.screenWidth;
    }

  },
  data:function(){
    return{
      platform: 'pc',
      drawer: false,
      direction: 'btt',
      // 浏览器宽度
      screenWidth :0,
      imgs:[
        {id:0,url:require('../assets/img/github.png'),link:'https://www.bilibili.com/'},
        {id:1,url:require('../assets/img/csdn.png'),link:'https://blog.csdn.net/weixin_48879513?spm=1000.2115.3001.5343'}
      ]
    }
  },
  mounted() {
    // 首次加载时,需要调用一次
    this.screenWidth =  window.innerWidth;
    this.setSize();
    // 窗口大小发生改变时,调用一次
    window.onresize = () =>{
      this.screenWidth =  window.innerWidth;
      this.setSize();
    }
  }
}
</script>
<style>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}
img{
  /*设置图片宽度和浏览器宽度一致*/
  width:100%;
  height:inherit;
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_48879513/article/details/121715905