Reputation: 2141
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?
For example:
<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.
Upvotes: 3
Views: 12024
Reputation: 3148
Yes, it's possible please go through the docs
Note: please use computed
, methods
instead of inline for better debugging
<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>
Upvotes: 8
Reputation: 2536
Of course it is possible as described here: https://v2.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>
Upvotes: 8