DaveL17
DaveL17

Reputation: 2017

Vue JS 3 Class Binding Does not Apply

In attempting to apply an example from the Vue 3 guide on class and style bindings, I'm unable to get class binding to work.

const App = {
  data() {
    return {
      message: 'Vue version: ' + Vue.version,
      classObj: {
        active: true,
        'text-danger': false
      }
    }
  }
}
Vue.createApp(App).mount('#result')
.active {
  color: #00FF00;
}

.text-danger {
  color: #FF0000;
}
<script src="https://unpkg.com/[email protected]"></script>

<div id="result" class="static" :class="classObj">{{ message }} <br> {{ classObj }}</div>
It appears that Vue is loading and the Vue app is returning classObj properly { "active": true, "text-danger": false }. Note that I'm printing the value of classObj to the DOM merely to inspect its value.

I have tried:

Upvotes: 1

Views: 1955

Answers (1)

akuiper
akuiper

Reputation: 214927

The issue here is you are trying to bind to attributes to the top level element that Vue instance is mounted to. Try move the reactive component to a child node:

const App = {
  data() {
    return {
      message: 'Vue version: ' + Vue.version,
      classObj: {
        active: true,
        'text-danger': false
      }
    }
  }
}
Vue.createApp(App).mount('#result')
.active {
  color: #00FF00;
}

.text-danger {
  color: #FF0000;
}
<script src="https://unpkg.com/[email protected]"></script>

<div id="result">
  <div class="static" :class="classObj">{{ message }} <br> {{ classObj }}</div>
</div>

Upvotes: 2

Related Questions