Vue spread an object as computed properties
10,585
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>
Author by
PROgram52bc
Updated on June 16, 2022Comments
-
PROgram52bc almost 2 years
I have an array of objects called
config
, and acurrentIdx
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!