如何访问Vue 3@click事件中的“this”组件?

lnvxswe2  于 2022-12-14  发布在  Vue.js
关注(0)|答案(3)|浏览(252)

我使用了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。

nbysray5

nbysray51#

简单地说,你不能。因为这个逻辑只与按钮组件本身相关,所以最好把这个逻辑保留在按钮组件中。添加一个 prop 并基于这个来呈现一些东西,就像你在评论中建议的那样,是一个很好的方法。

icomxhvb

icomxhvb2#

考虑其他选项

虽然我使用了@paddotk的答案,“ prop 的方式”来解决我的问题,我只是添加了这个答案,所以任何人谁读这个问题后,将有一个完整的答案。
据我所知,还有两种方法可以做到这一点:
1-正如@MrFabio_25在注解中提到的,我可以在子组件上创建一个自定义事件,并使用'this'作为参数$emit,这样我就可以在父组件中处理该事件:

// wbButton.vue file

<inside-wb-component ref="btnElement" @click="handleClick">
     <button>
          <slot></slot>
     </button>
</inside-wb-component>  

//and in the script tag
//...
methods:{
     handleClick(){
          this.$emit('buttonClick',this)
     }
}
//...

而只需在父组件中:

<wb-button @buttonClick="handleButtonClick">
     A text here
</wb-button>
// in the script tag
methods:{
     handleButtonClick(elem){
          elem.$refs.btnElement.putInLoadingStatus()
     }
}

2-第二种方法(不涉及子组件)是使用引用数组,如下所述:Vue 3文档-参考v-for内部

<div v-for="(item,key) in items" :key="key">
     <wb-button ref="wbButtonRefs" @click="handleButtonClick(item,key)">
          A text here
     </wb-button>
</div>
// and in scripts tag
//...
methods:{
     handleButtonClick(item,index){
          const buttonRef=this.$refs.wbButtonRefs[index]
          // Now do whatever with buttonRef
          buttonRef.$refs.btnElement.putInLoadingStatus()
     }
}
//...
pokxtpni

pokxtpni3#

<template>
   <button @click="test($event)">Test</button>
</template>


methods:{
     test(e){
          const comp = e.target.__vueParentComponent
          const props = comp.props
     }
}

相关问题