简体   繁体   English

如何在 Vue.js 的 2 个按钮中找到哪个按钮被点击?

[英]How to find which button was clicked among 2 buttons in Vue.js?

I have 2 buttons:我有2个按钮:

      <Button
              :disabled="disabled"
              :loading="isLoading1"
              @click="handleClick1"
              >Btn 1</Button>
          <Button
              :disabled="disabled"
              :loading="isLoading2"
              @click="handleClick2"
              >Btn 2</Button>
    
    computed: {
    isLoading1(){
    ...
    }
 isLoading2(){
    ...
    }
    methods:{
    handleClick1(){
    ...
    }
    handleClick2(){
    ...
    }
    }

The point is that both buttons have almost the same conditions for showing it loading.关键是两个按钮的显示条件几乎相同。 I need somehow to find which button was clicked for being able to show the loading case only for that button.我需要以某种方式找到点击了哪个按钮才能仅显示该按钮的加载情况。 How can I find which button was clicked?如何找到点击了哪个按钮? In other words, it should be loading only for the clicked button, not both buttons.换句话说,它应该只为点击的按钮加载,而不是两个按钮。 How can be this achieved either by somehow tracking the clicked button or by another way?如何通过某种方式跟踪点击的按钮或通过其他方式来实现这一点?

Add one handler for the two event clicks with a parameter:使用参数为两个事件点击添加一个处理程序:

 <Button
              :disabled="disabled"
              :loading="isLoading1"
              @click="handleClick(1)"
              >Btn 1</Button>
          <Button
              :disabled="disabled"
              :loading="isLoading2"
              @click="handleClick(2)"
              >Btn 2</Button>
    

in methods use that index to know the clicked button :在方法中使用该索引来了解点击的按钮:

 handleClick(index){
    ...
    }

What you can do is give each button an id:你可以做的是给每个按钮一个 id:

<Button
    id="button-1"
    :disabled="disabled"
    :loading="isLoading1"
    @click="handleClick"
>
    Btn 1
</Button>

<Button
    id="button-2"
    :disabled="disabled"
    :loading="isLoading2"
    @click="handleClick"
>
    Btn 2
</Button>

And then pass your click event into the click handler function and retrieve the id of the button that was clicked:然后将您的点击事件传递给点击处理函数并检索被点击的按钮的 id:

methods: {
    handleClick(e) {
        console.log(e.target.id)
        // If you want to to do something depending on the id:
        if (e.target.id === 'button-1') {
            this.doSomeMethod()
        } else if (e.target.id === 'button-2') {
            this.doSomeOtherMethod()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM