[Vuejs]-Which is the best way to use this script in the Vue.js?

1👍

Option 1 – $refs

For getting element from DOM use ref.
If you set in HTML for an element ref attribute, e.g. <button ref="myButton"> then you can change the style in the same way as in your code:
this.$refs.myButton.style.display="none"

Regarding loops: ref will help only if the elements with the same ref were created by v-for. In this case this.$refs.<your ref> will be an array. Example: let’s say you have images displayed by v-for with the same ref:

<img v-for="image in images" ref="imgSlide"...>

Then you can manipulate this.$refs.imgSlide as an array:

this.$refs.imgSlide.forEach(el => el.style.display = 'none')

Option 2 – Class and Style Bindings

Let’s say you have <img id='imgModal'...>. You want to change display in ‘openModal’ method.
Do the folowing steps:

  • Add style binding: <img id='imgModal' :style="{ display: displayValue }"...
  • Add binding variable in data and initialize it:
data: {
  displayValue: 'none'
}
  • Change the value of binding variable in the method:
openModal() {
  this.displayValue = 'block'
}

With this approach, you don’t need loops to change the style for multiple elements. Changing the binding variable will affect all elements bound with it.

Read more about Class and Style Bindings

Specifically for display = "none": Don’t hide elements by changing display explicitly. Use v-if or v-show instead.

👤Lana

Leave a comment