javascript - Vue.js 通过单击更改图像 src
问题描述
我需要有关切换图像的帮助。当我单击图像时,我希望它从源列表中更新,例如每次单击时从 4 个源中更新。因此,每次单击都会使用列表中的下一个源更新图像。我在 Vue 方面不是最好的,但我正在学习。我已经尝试过这样做,但还没有弄清楚。如果有人能告诉我如何在 Vue 代码中执行此操作,那将非常有帮助。
解决方案
这是如何在 vue 中解决图像切换的示例。
var app = new Vue({
el: "#app",
data() {
return {
index: 0,
image: null,
images: [{
id: 1,
src: "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg",
alt: "Natural Grove Green Trees Path"
},
{
id: 2,
src: "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg",
alt: "stockafbeelding cascades in nationaal park plitvice"
},
{
id: 3,
src: "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg",
alt: "natural view of waterfall"
}
]
}
},
mounted() {
this.switchImage();
},
methods: {
switchImage() {
this.image = this.images[this.index];
this.index = (this.index + 1) % this.images.length;
}
}
});
.image {
width: 100px;
height: 100px;
margin: 2px;
cursor: pointer;
transition: filter 0.3s ease-in;
}
.image:hover {
filter: brightness(1.2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<img v-if="image" :key="image.id" @click="switchImage" class="image" :src="image.src" alt="image.alt">
</div>
推荐阅读
- database - 如何将数据库从安装移动到新安装
- javascript - 如果 React Native Function 中的 prop 发生变化,则渲染
- linux - 出现错误:运行 cloudtracker --account demo --list users 时无法从配置文件 config.yaml 加载 yaml
- express - Express.js 的 next() 函数究竟做了什么,在 express 包中的具体位置是什么?
- django - '“错误:未找到 .egg-info 目录”在部署到 heroku 期间
- sql - 为什么将用户函数中的数据插入表变量时使用临时表更快?
- html - 如何在嵌套表上添加位置粘性?
- raspberry-pi - 用于 NXP 微控制器 (MKE06Z64VLH4) 的带覆盆子的 CAN 更新程序
- flutter - Flutter 2.0 用户在 Inkwell 上的点击未注册
- python - 如何从条目中获取值并注入 init 函数参数?