我很好奇,有没有可能在Vue.js中绑定内联样式?我很熟悉类绑定,但是如果有时出于某种原因你想要绑定一个内联的样式语句,是否可以像绑定类一样绑定它呢?
例如:
<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>在上面的例子中,当条件为真时,我想改变元素的背景。
发布于 2019-02-04 17:26:57
当然,这里所描述的也是可能的: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>发布于 2019-02-04 19:37:18
是的,可以通过docs
注意:为了更好地调试,请使用computed、methods而不是内联
<template>
<div>
<h1 :style="styleObject"> Text </h1>
<button @click='toggleCondition'>Click me</button>
</div>
</template>
<script>
export default {
data() {
return {
condition: false,
};
},
computed: {
styleObject() {
return this.condition ? { background: 'red' } : {};
},
},
methods: {
toggleCondition() {
this.condition = !this.condition;
},
},
};
</script><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
https://stackoverflow.com/questions/54513103
复制相似问题