3

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.

2 Answers 2

8

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>
Sign up to request clarification or add additional context in comments.

Comments

8

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>

1 Comment

Tnx, I'm still a bit new to vue so didn't go through all the docs and needed this real quick. You and Thomas made this very clear to me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.