Apply an Class by using VueJS condition

Viewed 348

I'm trying to apply a class to a <p> tag using a VueJS condition but it doesn't work at all, despite it working on JSfiddle. It's been 3 days now that I'm stuck, please help me.

VueJS (in main.js)

new Vue({
  el: "#test",
  data: {
    selected: "2"
  }
});

HTML (App.vue)

<div id="app">
  <div id="test">
    {{ selected }}
    <p :class="{ selection: 1 === selected }">
      heyyy 1
    </p>
    <p :class="{ selection: 2 == selected }">
      heyyy 2
    </p>
    <button @click="selected = 2">Switch</button>
  </div>
</div>
2 Answers

I'll assume you're using Vue-CLI since you have a .vue file, but your main.js is using syntax from Vue CDN. Maybe you copied the code from the fiddle instead.

I'll assume too that you have a CSS class named .selection for this to work.

Either way, App.vue has its own component instance which is not the main.js mounting instance (it's one level deeper). Your code creates selected in the mounting root instead of App.vue.

To fix, create it in App.vue <script> section instead:

<template>
<div id="app">
  <div id="test">
    {{ selected }}
    <p :class="{ selection: 1 === selected }">
      heyyy 1
    </p>
    <p :class="{ selection: 2 == selected }">
      heyyy 2
    </p>
    <button @click="selected = 2">Switch</button>
  </div>
</div>
</template>

<script>
export default {
  data() {
    return {
      selected: "2"
    }
  }
}
</script>

<style>
.selection {
  /* CSS */
}
</style>

to apply class binding in VueJs you can use it as :

:class="{ 'selection(your class name here)': selected === 1}"

Related