So I want to apply the class .testcolor to the div when testvalue is true and apply nothing when testvalue is false.
When I add the getClass method to :class it doesn't even get called, but does when called from {{ getClass }}. I've tried clearing the cache and even rewriting the entire code but still doesn't work! The complete code is as follows:
<!DOCTYPE html> <html> <head> <title>Vue Test</title> <style> .testcolor { color: red !important; } </style> </head> <body> <div id="test" :class="getClass"> <h1>Test stuff</h1> <h2>{{ testvalue }}</h2> </div> <script type="module"> import { createApp } from "https://unpkg.com/vue@3.2.19/dist/vue.esm-browser.js"; createApp({ data() { return { testvalue: true, }; }, methods: { getClass() { console.log("Method 'getClass' called"); return this.testvalue ? "testcolor" : ""; }, }, }).mount("#test"); </script> </body> </html>
I found that if I mount the Vue instance on a div element and add :class="testClass" (from the answer) to h2 it works! But when I install it on h2 element it doesn't work!
Edited based on your comment @martin0300
First, you need to wrap the partition in another partition whose id must be test. Vue does not consider the container element (the div with id
test
) to be part of the application and does not handle any directives. References mentioning this are left below.https://vuejs.org/guide/essentials/application .html#Install application
So change your markup to something like this to apply the value from the getClass method...
...or this way using the computed property method (described below.)
--
Original message:
getClass
Needs to be called when defined as a method, and the return value ("testcolor"
) is set to the value of :class. Note that the function callgetClass()
is used instead ofgetClass
.That said, this is not the preferred way to apply classes conditionally. We prefer computed properties to methods. A method is called on every render, whereas a computed property is only recalculated when the underlying reactive data it depends on changes (in this case, the computed property
testClass
depends on the reactive propertytestvalue代码>.
The idiomatic Vue code in your case is as follows. Note that computed properties are not called like functions as they are implemented internally using accessor methods/using JS proxies (
:class="testClass"
and NOT:class="testClass()"
). I believe the difference between how methods and computed properties are used is the cause of your confusion.