简体   繁体   中英

Using hasClass with vue.js

I know this setup I have isn't ideal however I need to check the class of an input element. I have just started using Vue.js on a new project however we have a form validation library that has to be used that uses jQuery.

The validation library I am using adds a class to an input if it doesn't fit some validation requirements.

If I was using jQuery I could just use hasClass to check if the input element had a specific class.

In Vue I am unsure how I can check if an element has a class though?

Here is an example method of what I'd like to achieve:

      methods: {
        nextStep: function() {
          const element = this.$el.querySelector("#conversation__tram-1 input");
          if (element has the class of is-valid) {
            Do something
          }

        },
      },

As you can see I'd like to check whether or not the input field has a class of is-valid . Can you think of any way I can do this with Vue.js? Thanks.

You can use the element's classList property :

if (element.classList.contains('is-valid')) {
  // Do something
}

Most of the native vue.js functions involve manipulating the data behind the DOM, not the DOM itself.

There are multiple ways you can achieve this,
You can use Vue class binding, which is two-way. So you once you initialize binding then you can build an API to expose that.

Have you tried this?

if (this.$els.elementNameHere.className.match(/\bmyclass\b/)) {
    //
}

If jQuery is already involved, just use its hasClass the way you already know how.

    nextStep: function() {
      const element = this.$el.querySelector("#conversation__tram-1 input");
      if ($(element).hasClass('is-valid')) {
        Do something
      }
    },

Vue does not provide any special DOM manipulation routines, because in Vue, you aren't generally supposed to be manipulating the DOM. There are some carved-out exceptions, but this isn't really one. :) The key to mixing jQuery and Vue is that you must be careful to separate what jQuery controls from what Vue controls so they don't step on each other's toes. Not much harm here in simply reading the DOM as long as you don't expect Vue to be updating it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM