Search code examples
vue.jsvuejs3liquid

Getting element (button) data attribute with vue3


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

  <div class="two columns">
    <button 
      data-value='{{ value }}'
      class="button-selection"
      :class="selectionButtonClass($event)"
      @click="selectionButton($event)" 
    >
      <span class="text">{{ 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.


Solution

  • $event is only available to event handlers. @click="selectionButton($event)" defines an inline event handler, while :class="selectionButtonClass($event)" 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 }}'
          class="button-selection"
          :class="selectionButtonClass($event)"
          @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.