我使用了Vue 3
,在一个v-for循环中,我创建了多个button元素。这些button是在另一个名为wb-button
的组件中创建的。所以我在每个v-for循环中都调用wb-button
。
我将@click事件侦听器添加到wb-button
中,该侦听器调用当前组件中的一个方法,简单来说:
<div v-for="(item,key) in items" :key="key">
<span>{{item.name}}</span>
<wb-button @click="deleteItem(item)">
Delete item!
</wb-button>
</div>
这是我想要的,当我想把wb-button
像一个ref一样传递给deleteItem
方法时,问题就开始了。目的是对wb-button
中的另一个ref进行修改。所以我基本上想做的是:
export default{
name: 'listComponent',
methods:{
async deleteItem(item,wbButtonRef){
// The next line is what I want to do
wbButtonRef.$refs.btnElement.putInLoadingStatus()
// do the delete item action
}
}
}
我知道我可以在每个wb-button
上创建一个ref,并向该方法传递一个ID或其他信息,但我不认为这是最干净的方法。
如果有什么东西可以把wb-button
元素作为方法参数传递,那就太好了。
<!-- I want to know if there is something I can put in
the second argument of the 'wb-button' @click event -->
<wb-button @click="deleteItem(item, /* what to put here?*/)">
<!-- "this","$this","$event.target" etc ... -->
我已经尝试了$event.target,但是它返回了wb-button
的根元素,我需要的是wb-button
本身,就像一个$ref。
3条答案
按热度按时间nbysray51#
简单地说,你不能。因为这个逻辑只与按钮组件本身相关,所以最好把这个逻辑保留在按钮组件中。添加一个 prop 并基于这个来呈现一些东西,就像你在评论中建议的那样,是一个很好的方法。
icomxhvb2#
考虑其他选项
虽然我使用了@paddotk的答案,“ prop 的方式”来解决我的问题,我只是添加了这个答案,所以任何人谁读这个问题后,将有一个完整的答案。
据我所知,还有两种方法可以做到这一点:
1-正如@MrFabio_25在注解中提到的,我可以在子组件上创建一个自定义事件,并使用'this'作为参数$emit,这样我就可以在父组件中处理该事件:
而只需在父组件中:
2-第二种方法(不涉及子组件)是使用引用数组,如下所述:Vue 3文档-参考v-for内部
pokxtpni3#