我的vue组件中有一个从API返回的图像数组,其迭代和显示方式如下:
<span v-for="pic in pics">
<img :src="'images/'+pic" onmouseover="highlight(pic)" :class="{isHovered = hovered}" />
</span>
在我的脚本中:
data(){
return {
pics: [],
hovered: false,
}
},
methods:{
highlight(pic){
this.hovered = true;
}
}
在我的CSS中
isHovered{
border: 2px solid red;
scale: 1.2;
cursor: pointer;
}
问题是每次我将鼠标悬停在一张图像上时,所有图像都获得isHovered类。我的意图是仅将悬停的图像绑定到isHovered类。 请问我在做什么错。任何指导将不胜感激。
答案 0 :(得分:5)
我正在阅读OP,但找不到答案,为什么不能仅使用CSS?为此,使用Vue的逻辑实在是太过分了。
// thanks to @C2486 for the snippet
var app = new Vue({
el: "#app",
data() {
return {
pics: [{
img: "https://i.ytimg.com/vi/qV6y1SksAcE/maxresdefault.jpg"
}, {
img: "http://www.memorandum.com/wp-content/uploads/2018/05/trunk-club-memorandum-closet-staples-chic-working-girl-professional-women-capsule-wardrobe-10.jpg"
}, {
img: "http://www.memorandum.com/wp-content/uploads/2018/07/top-working-women-career-sites-17-680x1020.jpg"
}]
}
}
});
.some-img-class:hover {
border: 3px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div v-for="(pic,index) in pics">
{{index+1}}
<img :src="pic.img" width="60" class="some-img-class" />
</div>
</div>
</div>
答案 1 :(得分:3)
在您的代码中,如果任何一个图像都悬停,您将尝试触发所有图像的正片效果,而且您在应用类时遇到语法错误。但是,实现这一目标的方法有很多,一种方法如下所示:
var app = new Vue({
el:"#app",
data(){
return {
pics: [{img:"https://i.ytimg.com/vi/qV6y1SksAcE/maxresdefault.jpg",hovered:false},{img:"http://www.memorandum.com/wp-content/uploads/2018/05/trunk-club-memorandum-closet-staples-chic-working-girl-professional-women-capsule-wardrobe-10.jpg",hovered:false},{img:"http://www.memorandum.com/wp-content/uploads/2018/07/top-working-women-career-sites-17-680x1020.jpg",hovered:false}],
hovered: false,
}
},
methods:{
}
});
.isHovered{
border:3px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div v-for="(pic,index) in pics">
{{index+1}}
<img :src="pic.img" v-on:mouseover="pic.hovered = true" :class="{isHovered:pic.hovered}" v-on:mouseout="pic.hovered = false" width="60"/>
</div>
</div>
</div>
答案 2 :(得分:2)
那是因为您在所有hovered
之间共享了一个pics
属性。您需要重新编写图片,以便每个图片都有自己的hovered
状态。例如..
data(){
return {
pics: [
{id: 0, name: 'pic1.jpg', hovered: false},
{id: 1, name: 'pic2.jpg', hovered: false},
{id: 2, name: 'pic3.jpg', hovered: false},
...
]
}
},
methods:{
toggleHighlight(pic){
pic.hovered = !pic.hovered;
}
}
然后,您可以在模板中引用各个hovered
状态..
<span v-for="pic in pics">
<img :src="'images/'+pic.name" onmouseover="toggleHighlight(pic)" :class="{isHovered: pic.hovered}" />
</span>