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

Time:05-03

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  :style="{ ...styleComputed }">
    item
  </div>
  
  <div  :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 };
    }
  }
})

CodePudding user response:

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  :style="{ ...styleComputed }">
    item
  </div>
  
  <div  :style="{ ...styleMethod('blue') }">
    item2
  </div>
</div>

CodePudding user response:

I guess that the destructuring breaks the reactivity?

You should use the array binding instead to bind multiple objects into class / style:

<div
  :style="[styledComputed, { opacity: 1 }]"
  :
>
</div>
  • Related