是否可以将内联样式与vue.js绑定?
问题描述:
我很好奇,是否可以在Vue.js中绑定内联样式?我对类绑定很熟悉,但是如果有时出于某种原因想要内联绑定样式语句,又有可能像对类一样进行绑定吗?
I am curious, is it possible to bind the inline style in Vue.js? I'm familiar with class binding but what if sometimes for some reason you want to bind a style statement inline, is it possible to bind it like you do with class?
例如,
<template>
<div>
<h1 :style="{('background:red') : condition}"> Text </h1>
<button @click='condition = true'>Click me</button>
</div>
</template>
<script>
export default {
data(){
return {
condition:false
}
}
}
</script>
在上面的示例中,我想在条件变为真时更改元素的背景.
In the example above I'd like to change the background of the element when the condition becomes true.
答
Of course it is possible as described here: https://vuejs.org/v2/guide/class-and-style.html
<template>
<div>
<h1 v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"> Text </h1>
<button @click='condition = true'>Click me</button>
</div>
</template>
<script>
export default {
data(){
return {
condition:false,
activeColor: 'white',
fontSize: 12
}
}
}
</script>