You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js条件绑定class失效,请求排查解决方法

Fixing Your Vue2 Class Binding Issue

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:09:35