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 = !availabletovalue = !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
- On page load,
valueis set totrue, so theavailableclass is applied—your span starts with a green background as expected. - When you click the div,
valueflips tofalse, removing theavailableclass, so the span reverts to its default red background. - Clicking again flips
valueback totrue, restoring the green background.
内容的提问来源于stack exchange,提问作者Osman Rafi
相关产品推荐
相关产品推荐

