简体   繁体   English

Vue将对象传播为计算属性

[英]Vue spread an object as computed properties

I have an array of objects called config , and a currentIdx property in my component. 我的组件中有一个名为config的对象数组,以及一个currentIdx属性。 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. 我认为问题在于computed需要功能,但是扩展语法(...)返回对象。 So, my question is: Is there any way to reduce the repetition in this case? 所以,我的问题是: 在这种情况下,有什么方法可以减少重复?

Thanks! 谢谢!

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM