Home > Back-end >  Getting element (button) data attribute with vue3
Getting element (button) data attribute with vue3

Time:07-16

I have the following html div. The {{ }} represent liquid syntax and it renders server side.

  <div >
    <button 
      data-value='{{ value }}'
      
      :
      @click="selectionButton($event)" 
    >
      <span >{{ value }}</span>
    </button>
  </div>

In a vue 3 instance I have the following method in the same page.

    selectionButtonClass(el) {
      console.log('checking val');
      console.log(el);
    }

My goal is to set a conditional class in the selectionButton method but I can't get the element to get the data attribute. The above appears in the console log as undefined. However the @click does show the event obviously it's recognize the onclick but not the class method check.

CodePudding user response:

$event is only available to event handlers. @click="selectionButton($event)" defines an inline event handler, while : is not an event handler.

To get the element, you need to add a ref attribute to the <button>:

    <button 
      ref="selectionButton"
      data-value='{{ value }}'
      
      :
      @click="selectionButton($event)" 
    >

And access it by this.$refs.selectionButton, assuming you are using the options API. However, the ref is available only after the component is mounted. Thus you need to handle the case where the ref is null.

More on template refs: https://vuejs.org/guide/essentials/template-refs.html

Since you are using server side rendering, I think it would be better to render the value as a parameter of the selectionButton function on the server side.

  • Related