有的时候业务需求,是动态切换图片。

而图片资源,有的时候是来自CDN托管资源的,有的时候是本地public存储的。整理了一下代码,接下来稍微分别展示一下

网络资源路径 & 本地静态资源路径

html布局

<!-- 网络资源图片路径 -->
<p>
	src 动态 网络路径
	<el-button @click="changeSrc('online')">切换</el-button>
</p>
<img :src="onlineSrc" />

<!-- 本地静态资源图片路径 -->
<p>
	src 动态 本地路径
	<el-button @click="changeSrc('offline')">切换</el-button>
</p>
<img :src="offlineSrc" />

关于图片资源,我单独给了一个变量进行统一存储管理。
ONLINE_SRC为网络资源路径
OFFLINE_SRC为本地静态资源路径
js

const ONLINE_SRC = [
  "http://touxiangkong.com/uploads/allimg/20203301301/2020/3/Vzuiy2.jpg",
  "http://touxiangkong.com/uploads/allimg/20203301301/2020/3/UbQbYn.jpg",
  "http://touxiangkong.com/uploads/allimg/20203301301/2020/3/Y3MVje.jpg",
  "http://touxiangkong.com/uploads/allimg/20203301301/2020/3/6Vz2yq.jpg",
  "http://touxiangkong.com/uploads/allimg/20203301301/2020/3/MzUfQ3.jpg",
  "http://touxiangkong.com/uploads/allimg/20203301301/2020/3/YNVjqi.jpg",
  "http://touxiangkong.com/uploads/allimg/20203301301/2020/3/aquEJb.jpg"
];


import img1 from "/public/images/1-6.jpg";
import img2 from "/public/images/2-6.jpg";
import img3 from "/public/images/3-6.jpg";
import img4 from "/public/images/4-6.jpg";
import img5 from "/public/images/dog.jpg";
const OFFLINE_SRC = [img1, img2, img3, img4, img5];
// const OFFLINE_SRC = [
//   "/public/images/1-6.jpg",
//   "/public/images/2-6.jpg",
//   "/public/images/3-6.jpg",
//   "/public/images/4-6.jpg",
//   "/public/images/dog.jpg"
// ];
export default {
  data() {
    return {
      online: 0,
      onlineSrc: "",
      offline: 0,
      offlineSrc: ""
    };
  },
  mounted() {
    this.onlineImg();
    this.offlineImg();
  },
  methods: {
    changeSrc(type) {
      if (type == "online") {
        this.online =
          this.online + 1 <= ONLINE_SRC.length - 1 ? this.online + 1 : 0;
        this.onlineImg();
      } else {
        this.offline =
          this.offline + 1 <= OFFLINE_SRC.length - 1 ? this.offline + 1 : 0;
        this.offlineImg();
      }
    },
    onlineImg() {
      this.onlineSrc = ONLINE_SRC[this.online];
    },
    offlineImg() {
      this.offlineSrc = OFFLINE_SRC[this.offline];
    }
  }
};

css

img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

默认展示如下:
在这里插入图片描述
各点击一次切换,效果如下:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐