Search code examples
vue.jsstylesspread

Can't apply dynamic styles to element using computed property or method


Trying to use spread operator in dynamic styles (not useful in this simplified example but important in my real case with multiple style objects). In addition I need to use a method with a parameter, but it doesn't work. In fact even with a computed property it doesn't work.

What am I doing wrong?

JSFiddle

Markup:

<div id="app">
  <div class="item" :style="{ ...styleComputed }">
    item
  </div>
  
  <div class="item" :style="{ ...styleMethod('red') }">
    item
  </div>
</div>

Script:

new Vue({
  el: "#app",
  computed: {
        styleComputed: function(){
        return { 'background-color': 'red' };
    }
  },
  methods: {
    styleMethod: function(val){
        return { 'background-color': val };
    }
  }
})

Solution

  • Like you can see from snippet you just forgot to reference vue:

    new Vue({
      el: "#app",
      computed: {
        styleComputed() {
          return { 'background-color': 'red' };
        }
      },
      methods: {
        styleMethod(val) {
          return { 'background-color': val };
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
    <div id="app">
      <div class="item" :style="{ ...styleComputed }">
        item
      </div>
      
      <div class="item" :style="{ ...styleMethod('blue') }">
        item2
      </div>
    </div>