How to add class in Vue.js?

by gideon.hauck , in category: JavaScript , 2 years ago

How to add class in Vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@gideon.hauck You can store a class name as variable in data/props and then change a variable value to add class in Vue.js, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
  <div>
    <p :class="className">Test P tag</p>
    <button @click="addClass">Add Class</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      className: "",
    };
  },
  methods: {
    addClass() {
      this.className = "text-center";
    },
  },
};
</script>
by yvonne.goyette , a year ago

@gideon.hauck 

You can add a class to an element in Vue.js by using the class binding. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
  <div :class="{ active: isActive }">
    This is an example of class binding.
  </div>
</template>

<script>
export default {
  data() {
    return {
      isActive: true
    };
  }
};
</script>


In the above example, the class active will be added to the div element if the isActive data property is set to true.