Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 851
Nick Maddren Avatar asked May 30 '17 13:05

Nick Maddren


People also ask

Can I mix jQuery and Vue?

In general, you can mix Vue. js and jQuery components on the same page, if necessary, but you shouldn't use jQuery to manipulate a Vue. js component.

Can you use vanilla JavaScript in Vue?

Vue is a JavaScript framework and therefore you can insert vanilla code anywhere in it and it will run perfectly fine.

Is VueJS good for web development?

Vue. js is one of the most popularly used JS frameworks for developing UIs and single-page applications. Developers prefer this progressive framework as it offers easy-to-use syntax and clean formatting styles. Besides, it also gets easily integrated into other infrastructure as well.

Can I use JavaScript in Vue?

In Vue. js, components can be written in HTML, CSS, and JavaScript without dividing them into separate files.


2 Answers

You can use the element's classList property:

if (element.classList.contains('is-valid')) {
  // Do something
}
like image 135
thanksd Avatar answered Oct 19 '22 03:10

thanksd


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/)) {
    //
}
like image 1
Gaurav Gandhi Avatar answered Oct 19 '22 01:10

Gaurav Gandhi