Javascript Ref仅获取最后一个元素-VueJS
我正在尝试获取所有具有“ref”属性但失败的元素。它只获取具有ref属性的最后一个元素,在本例中是带有“lastako”类的div。有没有办法把它们都作为一个元素数组?谢谢你的帮助 这是我的密码Javascript Ref仅获取最后一个元素-VueJS,javascript,vue.js,Javascript,Vue.js,我正在尝试获取所有具有“ref”属性但失败的元素。它只获取具有ref属性的最后一个元素,在本例中是带有“lastako”类的div。有没有办法把它们都作为一个元素数组?谢谢你的帮助 这是我的密码 <template> <section id="news"> <div id="newscontainer"> <div class="latestevent pt-4"> &
<template>
<section id="news">
<div id="newscontainer">
<div class="latestevent pt-4">
<h1 class="latestnews">LATEST NEWS AND EVENTS</h1>
<span class="float-right readall">Read all news</span>
</div>
<div>
<div class="ako animated" ref="newsanimate" :style="'background-image: url('+getimgurl('bell.jpg')+')'">
<div class="akodesc">
<p><a href="#">BELL Blue Day</a></p>
</div>
</div>
</div>
<div>
<div class="ako animated" ref="newsanimate" :style="'background-image: url('+getimgurl('family.jpg')+')'">
<div class="akodesc">
<p><a href="#">Family Day</a></p>
</div>
</div>
</div>
<div>
<div class="ako animated lastako" ref="newsanimate" :style="'background-image: url('+getimgurl('flores.jpg')+')'">
<div class="akodesc">
<p><a href="#">Q Flores de Mayo</a></p>
</div>
</div>
</div>
</div>
</section>
</template>
如果以这种方式使用,则会覆盖以前的参照。如果希望您的
newsanimate
ref是一个数组,则使用v-for
和ref=“newsanimate”
类似于本例:
<div v-for="i in 3" :class="`test${i}`" ref="newsanimate">{{i}}</div>
{{i}
这里有一把小提琴:根据Vue.js文档: 当在具有
v-for
的元素/组件上使用时,注册的引用将是包含DOM节点或组件实例的数组
因此,在您的例子中,因为您没有使用v-for
定义div,所以前面的所有引用都会被后面的引用覆盖
请参阅以获取更多参考。如果要将这些标记设置为相同的
ref
名称,应将它们放置在v-for
中,以便Vue以数组的形式存储它们
此外,如果您想在该数组中区分它们。您可以使用:ref=“”
代替ref=“”
,例如
因此,如果你真的想得到你想要的。只需将[0]中的v-for=“i”:key=“i”
添加到父级
。例如
<template>
<section id="news">
<div id="newscontainer" v-for="i in [0]" :key="i">
<div class="latestevent pt-4">
<h1 class="latestnews">LATEST NEWS AND EVENTS</h1>
<span class="float-right readall">Read all news</span>
</div>
<div>
<div class="ako animated" ref="newsanimate" :style="'background-image: url('+getimgurl('bell.jpg')+')'">
<div class="akodesc">
<p><a href="#">BELL Blue Day</a></p>
</div>
</div>
</div>
<div>
<div class="ako animated" ref="newsanimate" :style="'background-image: url('+getimgurl('family.jpg')+')'">
<div class="akodesc">
<p><a href="#">Family Day</a></p>
</div>
</div>
</div>
<div>
<div class="ako animated lastako" ref="newsanimate" :style="'background-image: url('+getimgurl('flores.jpg')+')'">
<div class="akodesc">
<p><a href="#">Q Flores de Mayo</a></p>
</div>
</div>
</div>
</div>
</section>
</template>
最新新闻和事件
阅读所有新闻
可能与此无关。但非常重要的是,您需要设置:key=“”,以获得正确的ref
<template v-for="(item, index) in items">
<Item :key="index" ... ref>
<button ref... >
您试图对引用的元素执行什么操作?人们正在给你答案,但我很好奇你为什么做出这个决定。也许有另一种方法可以不用引用来完成同样的事情。
<template v-for="(item, index) in items">
<Item :key="index" ... ref>
<button ref... >