Home > Mobile >  Vue2 how to use $refs to target an element and remove css class
Vue2 how to use $refs to target an element and remove css class

Time:12-07

I want to remove the css class of an element when a method is called. but I want to do this using $refs.

template:

  <div class="modal"  ref="myModal"></div>

method:

      closeDropdown: function() {
            this.$refs.myModal.$el.removeClass("open");
      }

CodePudding user response:

this.$refs.myModal.classList.remove("open");

CodePudding user response:

Two steps:

  1. const modalElement = this.$refs.myModal; // reference to the DOM element
  2. modalElement.classList.toggle("custom"); // use classList API of DOM element

classList API reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList, you can use this API to modify its classes using the add(), remove(), replace(), and toggle() methods.

You can also refer to this CodeSandbox Vuejs example: https://codesandbox.io/s/nervous-wood-s3nhq?file=/src/App.vue:269-481

  • Related