Gharbi
Gharbi

Reputation: 135

Dynamic style text color with Vue.js

This code is in Angular

<div [style.color]="'#' + prod.id.substring(0,6)">
  <small>{{ prod.id }}</small>
</div>

I need to write a similar code with vue.js.

Upvotes: 5

Views: 9799

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115202

You can set style attributes using an object(key as CSS property and value as CSS value).

<div :style="{ color : '#' + prod.id.substring(0,6) }">
    <small>{{ prod.id }}</small>
</div>

Upvotes: 4

Loi Nguyen Huynh
Loi Nguyen Huynh

Reputation: 9928

3 syntaxes you can use:

<div :style="{ color: '#' + prod.id.substring(0,6)}">
  <small>{{ prod.id }}</small>
</div>
<div :style="`color: #${prod.id.substring(0,6)}`">
  <small>{{ prod.id }}</small>
</div>
<div :style="'color: #' + prod.id.substring(0,6)">
  <small>{{ prod.id }}</small>
</div>

Note: :style is equivalent to v-bind:style

Reference: https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax-1


Demo:

new Vue({
  el: '#app1',
  data: { hex: '0f0' }
});
button {
  width: 300px;
  height: 100px;
  font-size: 5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app1">
  <button :style="{ color: '#' + hex}">Button1</button>
  <button :style="`color: #${hex}`">Button2</button>
  <button :style="'color: #' + hex">Button3</button>
</div>

Upvotes: 2

Related Questions