Reputation: 2017
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>
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:
classObj
payload directly in the div statement with the same outcome (placing the object { "active": true, "text-danger": false }
as the class attribute in the <div>
.Upvotes: 1
Views: 1955
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