5

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.

2 Answers 2

4

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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>

4 Comments

Thank you but I need to do it using color code from a variable value
They're hex in my runnable demo, or prod.id.substring(0,6) in the sample.
I'm sorry but I didn't get it, I'll try it
@Gharbi it's exact same as the accepted answer, just give some more options.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.