2

I currently have this div:

 <div class="center-align" :class="setDisplay()">
    <div class="lds-hourglass"></div>
  </div>

I need to check if "this" div contains "center-aligh" to execute code in setDisplay:

In my Vue 3 setup I have:

setup() {
  const setDisplay = () => {
    console.log(this.$el);
  }
}
return {
  setDisplay
}

this.$el returns as undefined. From what I've read I would return it like so: this.$el.className based on this answer But it's not working. Any idea what I'm doing wrong?

1
  • 1
    Setup is called before the DOM node is rendered, you probably want a different lifecycle hook. Commented Sep 20, 2022 at 20:18

1 Answer 1

1

You can use ref in setup function and with nextTick get class in mounted hook with value.classList :

const { ref, onMounted, nextTick } = Vue
const app = Vue.createApp({
  setup() {
    const el = ref(null)
    const myClass = ref(null)
    
    const setDisplay = () => {
      myClass.value = 'myclass'
    }
    
    onMounted(async () => {
      await nextTick()
      console.log(Array.from(el.value.classList))
      Array.from(el.value.classList).includes('center-align') &&  setDisplay()
    })
    
    return { setDisplay, el, myClass }
  }
})
app.mount('#demo')
.myclass {
  color: red;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="center-align xxx" ref="el" :class="myClass">
    <div class="lds-hourglass"></div>
    class applied
  </div>
</div>

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

2 Comments

Thank you so much but the question was how to get the class not apply a class.
@FabricioG hey mate, check again pls, I updated my answer

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.