Home > Mobile >  Javascript method document.querySelector alternative in VueJs for optimization
Javascript method document.querySelector alternative in VueJs for optimization

Time:02-08

I need to optimize my code with all features of VueJs, so i've changed all the document.getElementById and document.querySelectorAll by using the ref in VueJs

So the only thing that i dont found an alternative is how to change : document.querySelector with another code related to VueJs :

document.querySelector('.mc-layer__content').classList.add('disable-scroll')

Is there any optimization related to this ?

Another important point, i can't use the ref here because the class is in the parent no in the component, so when i use this.$refs i can't see the parent element.

CodePudding user response:

The solution that i've foud is to use the store because the parent isnt direct :

In the child component instead to use document.querySelector,

document.querySelector('.mc-layer__content').classList.remove('disable-scroll')

i've used :

this.$store.dispatch('app/disableScroll')

And in the parent, i've add the dynamic class :

:

The variable isDisabled has been managed in the store with disableScroll variable like this:

disableScroll(state) {
      state.disableScroll = true
    },
    enableScroll(state) {
      state.disableScroll = false
    },

CodePudding user response:

Try with class binding:

new Vue({
  el: "#demo",
  data () {
    return {
      scroll: true
    }
  }
})
.disable-scroll {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <button @click="scroll = !scroll">switch</button>
  <div  :>
    ssssss
  </div>
</div>

  •  Tags:  
  • Related