1

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.

1
  • You don't really need to access the data-value attribute because liquid already has its value (i.e, {{ value }}). Can't liquid just render the button with the class based on value? Commented Jul 14, 2022 at 1:40

1 Answer 1

2

$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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.