最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic style text color with Vue.js - Stack Overflow

programmeradmin7浏览0评论

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.

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.

Share Improve this question edited Dec 25, 2019 at 12:37 adiga 35.3k9 gold badges65 silver badges87 bronze badges asked Dec 25, 2019 at 12:32 GharbiGharbi 1353 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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>

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/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./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>

发布评论

评论列表(0)

  1. 暂无评论