Vue.js条件绑定class失效,请求排查解决方法
Hey there! Let's get that class binding working for you. The problem here is a small but crucial detail in your ternary expression.
You wrote:
<div v-bind:class="[currentPage === 'help' ? highlight : '']">
The issue is that highlight is being treated as a data property variable here, but your Vue instance doesn't have a highlight property defined in its data object. So when the condition evaluates to true, Vue tries to reference an undefined variable, which results in an empty string instead of the class name you want.
The Fix
Wrap highlight in single quotes to treat it as a string literal (the actual class name you want to apply):
<div v-bind:class="[currentPage === 'help' ? 'highlight' : '']">
A Cleaner Alternative
Vue also supports an object syntax for class bindings that's often more readable for simple conditional classes. You can rewrite this as:
<div v-bind:class="{ highlight: currentPage === 'help' }">
Here, the key highlight is the class name, and the value currentPage === 'help' is the condition that determines whether the class is applied. This avoids the empty string case entirely and makes your intent clearer.
With either fix, since your currentPage is set to 'help' in the Vue instance, the highlight class should now be applied correctly to your div.
内容的提问来源于stack exchange,提问作者Bruno

