如何从具有 Vue.js 的单个文件组件中的方法访问计算的 属性
How to access a computed property from a method in a Single File Component with Vue.js
我有一个普通的单文件组件,它有一个计算的属性和一些方法:
<template>...</template>
<script>
...
export default {
props: ['matches'],
data: function() {...} // No problem with these
computed: {
formattedMatches: function () {
let formatted = [];
this.matches.forEach(function($match, $i, $arr) {
formatted[$i] = $match[0];
};
});
return formatted;
}
...
methods: {
getData: function() {
return this.formattedMatches();
},
...
}
}
<script>
当我尝试从方法 访问 this.formattedMatches()
时,我得到一个 [Vue warn]: Error in render: "TypeError: this.formattedMatches is not a function"
.
实现我想要的正确方法是什么?
提前致谢。
您可以像 property
那样访问计算属性,而不是像 method
:
// correct
console.log(this.myProperty);
// wrong
console.log(this.myProperty());
注意:如果您将其视为穿刺方法()
,它将抛出这样的错误Error in v-on handler: "TypeError: this.myProperty is not a function"
。
我有一个普通的单文件组件,它有一个计算的属性和一些方法:
<template>...</template>
<script>
...
export default {
props: ['matches'],
data: function() {...} // No problem with these
computed: {
formattedMatches: function () {
let formatted = [];
this.matches.forEach(function($match, $i, $arr) {
formatted[$i] = $match[0];
};
});
return formatted;
}
...
methods: {
getData: function() {
return this.formattedMatches();
},
...
}
}
<script>
当我尝试从方法 访问 this.formattedMatches()
时,我得到一个 [Vue warn]: Error in render: "TypeError: this.formattedMatches is not a function"
.
实现我想要的正确方法是什么? 提前致谢。
您可以像 property
那样访问计算属性,而不是像 method
:
// correct
console.log(this.myProperty);
// wrong
console.log(this.myProperty());
注意:如果您将其视为穿刺方法()
,它将抛出这样的错误Error in v-on handler: "TypeError: this.myProperty is not a function"
。