gpt4 book ai didi

css - VueJS : use data value in style

转载 作者:行者123 更新时间:2023-12-05 03:38:06 25 4
gpt4 key购买 nike

如何使用 data() <style>..</style> 中的值?我尝试了几种组合(带/不带 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>

最佳答案

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

关于css - VueJS : use data value in style,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69077889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com