如何使用Vue.js从单个文件组件中的方法访问计算属性

and*_*dcl 14 computed-properties vue-component vuejs2

我有一个普通的单个文件组件,该组件同时具有计算属性和一些方法

<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>
Run Code Online (Sandbox Code Playgroud)

当我尝试this.formattedMatches() 从该方法访问时,出现错误消息[Vue warn]: Error in render: "TypeError: this.formattedMatches is not a function"

实现我想要的正确方法是什么?提前致谢。

mor*_*eli 17

您可以像属性一样访问计算的属性,而不是方法:

// correct    
console.log(this.myProperty);

// wrong    
console.log(this.myProperty());
Run Code Online (Sandbox Code Playgroud)

  • dang如何知道只需要属性总是作为方法尝试,谢谢 (2认同)