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

Vue点击切换HTML类功能失效,请求排查代码错误

Fixing Your Vue Dynamic Class Toggle Issue

Let's break down what's going wrong here and fix it step by step:

The Core Problem

Looking at your code, you're binding the available class to the value data property, but your click handler is trying to toggle a variable called available which doesn't exist in your Vue instance's data. That's why you're seeing errors—Vue can't find that variable to update!

Corrected Code

Here's the fixed version that does exactly what you want:

<!DOCTYPE html>
<html>
<head>
  <!-- Make sure you include Vue first! -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <style>
    span {
      background: red;
      color: #fff;
      padding: 8px 16px;
      cursor: pointer;
    }
    .available span {
      background: green;
    }
  </style>
</head>
<body>
  <div id="app5">
    <h1>Dynamic CSS</h1>
    <h2>Example 1</h2>
    <!-- Bind class to `value`, toggle `value` on click -->
    <div v-bind:class="{available: value}" v-on:click="value = !value">
      <span>Click</span>
    </div>
  </div>

  <script>
    var app5 = new Vue({
      el: '#app5',
      data: {
        value: true, // Starts as true, so initial class is active (green)
        nearby: false
      }
    });
  </script>
</body>
</html>

Key Changes Made

  • Updated the click handler: Changed available = !available to value = !value—we need to toggle the same property that's controlling the class binding.
  • Added proper document structure: Wrapped everything in a full HTML document and included the Vue CDN (this ensures Vue is loaded correctly, which is a common oversight).
  • Minor CSS tweaks: Added padding and cursor style to make the clickable area more intuitive for users.

How It Works

  1. On page load, value is set to true, so the available class is applied—your span starts with a green background as expected.
  2. When you click the div, value flips to false, removing the available class, so the span reverts to its default red background.
  3. Clicking again flips value back to true, restoring the green background.

内容的提问来源于stack exchange,提问作者Osman Rafi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:42:56