邓皓天*_*邓皓天 4 javascript ecmascript-6 vue.js spread-syntax vue-cli
我的组件中有一个名为 的对象数组config和一个currentIdx属性。然后我发现自己需要这样做:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试将所有功能替换为:
computed: {
...this.config[this.currentIdx]
}
Run Code Online (Sandbox Code Playgroud)
它通过了编译,但我在浏览器控制台中出现错误。我认为问题在于computed需要函数,但扩展语法 (...) 返回对象。所以,我的问题是:在这种情况下,有没有办法减少重复?
谢谢!
计算值可以返回对象,它们只需要由函数返回。如果这不是您想要的,请告诉我,我会看看我能做些什么来帮助您!
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];
}
}
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8475 次 |
| 最近记录: |