and*_*dcl 1 vue.js computed-properties vuejs2
也许是一个明显的,但我有一个像这样的Vue单文件组件:
<template>
...
</template>
<script>
export default {
props: [ 'matches', 'results' ],
computed: {
formattedMatches: function () {
let rows = [];
this.matches.forEach(function($match, $i) {
rows[$i] = {
id: $i + 1,
title: $match[0] + ' ' + $match[1]
};
});
return rows;
},
formattedResults: function () {
let rows = [];
this.results.forEach(function($resultRow, $i) {
rows[$i] = {
id: $i + 1,
title: this.formattedMatches[$i]
// Error in render: "TypeError: Cannot read property 'formattedMatches' of undefined"
};
});
return rows;
},
...
</script>
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用this.matches,错误也会出现,而不仅仅是this.formattedMatches.我想这是类和方法中变量范围的问题,但我甚至不知道是否有另一种更好的方法或模式来实现相同的行为.
有任何想法吗?提前致谢.
this在匿名函数中有不同的上下文forEach.最简单的解决方法是使用箭头函数表示法.
this.results.forEach(($resultRow, $i) => {
rows[$i] = {
id: $i + 1,
title: this.formattedMatches[$i]
};
});
Run Code Online (Sandbox Code Playgroud)