VueJS: 在样式中使用数据值

3

如何在 <style>..</style> 中使用 data() 的数值?我尝试了多种组合(带/不带 this,带/不带 {{brackets}} 等),但无法使其工作。然而,如果我输入像 '#f00' 这样的值,它就能正常工作。

我建立了一个这样的模板:

<template>
 <ul class="striped">
     <li>foo</li>
     <li>bar</li>
     <li>foobar</li>
</ul>


</template>

<style>
 ul.striped> li:nth-of-type(odd) {
    background-color: this.colors[0].backgroundcolor;  //dynamic value from data()
}
</style>

<script>

  data() {
    return {

        colors: [{'backgroundcolor':'#def'}], //simplified version for explanation
[..]
</script>
1个回答

3

随着 Vue 3.2 版本的发布,你可以直接使用基于状态驱动的动态 CSS,如下:

<template>
    <ul class="striped">
        <li>foo</li>
        <li>bar</li>
        <li>foobar</li>
    </ul>
</template>

<style>
    ul.striped> li:nth-of-type(odd) {
        background-color: v-bind('colors[0]')
    }
</style>

<script>
    data() {
        return {
            colors: ['#def'],
        }
    }
</script>

如果您使用的是Vue 2,您可以像这样使用CSS自定义属性
<template>
    <ul class="striped" :style="`--color: ${colors[0]}`">
        <li>foo</li>
        <li>bar</li>
        <li>foobar</li>
    </ul>
</template>

<style>
    ul.striped> li:nth-of-type(odd) {
        background-color: var(--color)
    }
</style>

<script>
   export default {
      data() {
        return {
            colors: ['#def'],
        }
    }
   }
</script>

非常好,谢谢你提供的两个版本,运行得很顺利。 - Dominic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接