How to bind style class in Vuejs


An ideal vue component may consist of three sections as in angular, template, Script, Style. We can bind styles according to some rules ( truthiness).

In the following example we place two different colors for text area border.


<style scoped>
.text-safe {
  border-color: green;
  color: black;
}

.text-not-safe {
  border-color: crimson;
  color: black;
}
</style>

In the textarea we conditionally render the style as follows

 <textarea
            :class="{
              'text-safe': getTweetQuota > 50
            }"
            placeholder="tweet text here"
            id="newTweet"
            rows="7"
            v-model="newTweetContent"
          />

Here the style text-safe is only enabled when the getTweetQuota value is greater than 50 otherwise the style class is get removed. We can also bind multiple style to a component as follows

 <textarea
            :class="{
              'text-safe': getTweetQuota > 50,
              'text-not-safe': getTweetQuota < 50,
            }"
            placeholder="tweet text here"
            id="newTweet"
            rows="7"
            v-model="newTweetContent"
          />

Todo:

Try to add different color to a button based on values in a Text input

The following vue post posts may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.