【发布时间】:2019-02-17 08:16:24
【问题描述】:
在计算属性中定义变量对 Vue 组件的性能有影响吗?
背景:我构建了一个表格组件,它通常根据传递的数据生成一个 HTML 表格,并且每列有不同的过滤器、整个表格的过滤器、排序键等,所以我在计算属性中定义了很多局部变量。
想象有一个对象数组:
let data = [
{ id: "y", a: 1, b: 2, c: 3 },
{ id: "z", a: 11, b: 22, c: 33 }
]
..Vue 组件使用它来显示数据:
<template>
<div>
<input type="text" v-model="filterKey" />
</div>
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr v-for="item in filteredData" :key="item.id">
<td v-for="(value, key) in item" :key="key">
{{ value }}
</td>
</tr>
</tbody>
</table>
</template>
数据通过输入过滤:
<script>
export default {
props: {
passedData: Array,
},
data() {
return {
filterKey: null,
};
},
computed: {
filteredData() {
// defining local scope variables
let data = this.passedData;
let filterKey = this.filterKey;
data = data.filter((e) => {
// filter by filterKey or this.filterKey
});
return data;
},
},
};
</script>
我的问题指的是let data = .. 和let filterKey = ..,因为filteredData() 会因filterKey(在data() 中定义)的任何更改而触发,因此局部变量也会更新,尽管它们不是“反应式” " 以 Vue 的方式。
在计算属性中定义局部变量时对性能有影响吗?您是否应该直接在计算属性内部使用来自data()(例如this.filterKey)的反应变量?
【问题讨论】:
标签: performance vue.js vuejs2 computed-properties