可以使用计算属性或方法将动态样式应用于元素
试图在动态样式中使用传播操作员(在这个简化的示例中不用有用,但在我的真实情况中使用多种样式对象很重要)。此外,我需要使用带有参数的方法,但它不起作用。实际上,即使有一个计算的属性,它也无效。
我在做什么错?
https://jsfiddle.net/goldorak/79wrj301/2/
<div id="app">
<div class="item" :style="{ ...styleComputed }">
item
</div>
<div class="item" :style="{ ...styleMethod('red') }">
item
</div>
</div>
”
new Vue({
el: "#app",
computed: {
styleComputed: function(){
return { 'background-color': 'red' };
}
},
methods: {
styleMethod: function(val){
return { 'background-color': val };
}
}
})
Trying to use spread operator in dynamic styles (not useful in this simplified example but important in my real case with multiple style objects). In addition I need to use a method with a parameter, but it doesn't work. In fact even with a computed property it doesn't work.
What am I doing wrong?
Markup:
<div id="app">
<div class="item" :style="{ ...styleComputed }">
item
</div>
<div class="item" :style="{ ...styleMethod('red') }">
item
</div>
</div>
Script:
new Vue({
el: "#app",
computed: {
styleComputed: function(){
return { 'background-color': 'red' };
}
},
methods: {
styleMethod: function(val){
return { 'background-color': val };
}
}
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就像您可以从摘要中看到的那样,您只是忘了参考Vue:
Like you can see from snippet you just forgot to reference vue:
我猜破坏性打破了反应性吗?
您应该使用数组绑定,而是将多个对象绑定到类 /样式中:
I guess that the destructuring breaks the reactivity?
You should use the array binding instead to bind multiple objects into class / style: