【问题标题】:VueJS: use data value in styleVueJS:在样式中使用数据值
【发布时间】:2021-11-03 17:47:22
【问题描述】:

如何在<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>

【问题讨论】:

    标签: css vue.js styles


    【解决方案1】:

    使用Vue 3.2 release,您可以像这样使用State-Driven Dynamic 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 custom properties

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

    【讨论】:

    • 非常好,谢谢你的两个版本,就像一个魅力。
    猜你喜欢
    • 2020-09-21
    • 2017-05-30
    • 2018-09-06
    • 2019-09-25
    • 1970-01-01
    • 2020-02-15
    • 2017-12-19
    • 2018-10-21
    • 2021-01-11
    相关资源
    最近更新 更多