[英]Component function works only on the first component Vue.js
I'm learning Vue.js and as exercise i'm developing a SPA. 我正在学习Vue.js,而我正在开发SPA。 I recursively add some icon as imgs via components.
我通过组件递归添加一些图标作为imgs。 (a lot of code has been omitted to focus on the problem)
(已经省略了很多代码来关注这个问题)
Vue.js Vue.js
Vue.component('icon', {
template:
'<img id="logo-icon" v-on:mouseover="animation"
class="platform_button" width="50" height="50"
src="../assets/img/logos/Android_icon.png" alt="img" />',
methods: {
animation: function(){
animate("#logo-icon","animated bounce")
}
}
})
new Vue({
el: '#apps'
})
...
.html html的
<div id="apps">
...
<div v-for="(el, in) in x" style="width:50%">
<icon></icon>
</div>
...
</div>
All images are shown properly. 所有图像都正确显示。 I want to start an animation on mouse hover the image.
我想在鼠标悬停图像时启动动画。 The function to animate works fine, problem is that regardless of which image I hover with the mouse, only the first one will bounce .
动画的功能很好,问题是无论我用鼠标悬停哪个图像, 只有第一个会反弹 。 Eg if I'm on img1 with the mouse, img1 will bounce.
例如,如果我使用鼠标img1,img1将反弹。 If I'm on img5 with the mouse, img1 will bounce instead of img5.
如果我使用鼠标img5,img1将反弹而不是img5。 How can I make animate only the image covered by mouse?
如何仅为鼠标覆盖的图像制作动画?
As the commenters pointed out, since you are applying the animation to #logo-icon
, and you have multiple copies of your component on the page, there are multiple img
tags that match #logo-icon
. 正如评论者指出的那样,由于您将动画应用于
#logo-icon
,并且您在页面上有多个组件副本,因此有多个img
标签与#logo-icon
匹配。 As such the behavior of animate
may affect just a single element (the first) or more than one, depending on implementation. 因此,
animate
的行为可能仅影响单个元素(第一个)或多个元素,具体取决于实现。
Instead, with Vue, you can just refer to the root element via this.$el
. 相反,使用Vue,你可以通过
this.$el
来引用根元素this.$el
。 This is a reference to the single specific img
element you want to animate. 这是对要设置动画的单个特定
img
元素的引用。
Vue.component('icon', {
template:
'<img id="logo-icon" v-on:mouseover="animation"
class="platform_button" width="50" height="50"
src="../assets/img/logos/Android_icon.png" alt="img" />',
methods: {
animation: function(){
animate(this.$el,"animated bounce")
}
}
})
What this does is apply the animation to the root element of your component. 这样做是将动画应用于组件的根元素。 In this case, the root element is your
img
. 在这种情况下,根元素是你的
img
。 If you had more than one element in your component you would likely need to use a ref. 如果组件中有多个元素,则可能需要使用ref。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.