Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue spread an object as computed properties

I have an array of objects called config, and a currentIdx property in my component. Then I found myself needing to do this:

computed: {
    textStyle: function() {
        return this.config[this.currentIdx].textStyle;
    },
    text: function() {
        return this.config[this.currentIdx].text;
    },
    key: function() {
        return this.config[this.currentIdx].key;
    }
}

I tried replacing all functions with:

computed: {
    ...this.config[this.currentIdx]
}

It passed the compilation, but I got an error in the browser console. I think the problem is that computed requires functions, but the spread syntax (...) returns objects. So, my question is: Is there any way to reduce the repetition in this case?

Thanks!

like image 273
PROgram52bc Avatar asked Jan 27 '23 23:01

PROgram52bc


1 Answers

Computed values can return objects, they just need to be returned by the function. Let me know if this isn't what you intended and I'll see what I can do to help!

let vm = new Vue({
  el : "#root",
  data : {
    current : 0,
    arrs : [
      {
        color : "background-color: blue;",
        text : "Dabodee Dabodai"
      },
      {
        color : "background-color: red;",
        text : "Angry"
      },
      {
        color : "background-color: green;",
        text : "See it works!"
      }
    ]
  },
  computed : {
    currentObject : function() {
      return this.arrs[this.current];
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root">
  <input type="number" v-model="current" min="0" max="2">
  <p :style="currentObject.color">
    {{ currentObject.text }}
  </p>
</div>
like image 191
Matthew Ludwig Avatar answered Jan 29 '23 13:01

Matthew Ludwig