Home > Blockchain >  How to get class name from current binded element using Vue
How to get class name from current binded element using Vue

Time:09-21

I currently have this div:

 <div  :>
    <div ></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?

CodePudding user response:

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  ref="el" :>
    <div ></div>
    class applied
  </div>
</div>

  • Related