With this div declaration:
JavaScript
x
2
1
<div v-bind:class="[currentPage === 'help' ? highlight : '']">
2
that I build accordingly to: https://v2.vuejs.org/v2/guide/class-and-style.html#Array-Syntax
But the binding isn’t working (the class ‘highlight’ never applied regardless of the currentPage
value).
I have this model where there is the currentPage
variable keeping track of the active page:
JavaScript
1
5
1
var vueApp = new Vue({
2
el: '#vueApp',
3
data: {
4
currentPage: 'help',
5
How can I activate the binding of a class on an element, based on the string value of a vue property?
Advertisement
Answer
In the template:
JavaScript
1
2
1
<div v-bind:class="[currentPage === 'help' ? highlight : '']">
2
highlight
is an identifier.
Thus, such expression expects that highlight
is property of the Vue instance/component. It is being evaluated, but since it probably is empty (undefined
) you get nothing.
Since you want the string, do:
JavaScript
1
2
1
<div v-bind:class="[currentPage === 'help' ? 'highlight' : '']">
2
Demo:
JavaScript
1
6
1
new Vue({
2
el: '#vueApp',
3
data: {
4
currentPage: 'help',
5
}
6
})
JavaScript
1
1
1
.highlight { background-color: yellow }
JavaScript
1
5
1
<script src="https://unpkg.com/vue"></script>
2
3
<div id="vueApp">
4
<div v-bind:class="[currentPage === 'help' ? 'highlight' : '']">Hello</div>
5
</div>