我很好奇,是有可能在绑定的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>
在上面的例子中我想改变元素的背景当条件变为真。
当然,这里描述的是可能的: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>
是的,这可能请到通过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>