【问题标题】:How to access a computed property from a method in a Single File Component with Vue.js如何使用 Vue.js 从单个文件组件中的方法访问计算属性
【发布时间】:2019-02-23 23:22:14
【问题描述】:

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

<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 是一种属性,而不是一种方法,因此请将this.formattedMatches() 更改为this.formattedMatches
  • 谢谢,问题解决了,你说得对

标签: vuejs2 vue-component computed-properties


【解决方案1】:

您可以像 property 那样访问计算属性,而不是像 method 那样:

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

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

注意:如果您将其视为带有穿刺术的方法(),它将抛出类似Error in v-on handler: "TypeError: this.myProperty is not a function"的错误。

【讨论】:

  • dang 如何知道只需要属性作为方法尝试,谢谢
猜你喜欢
  • 2018-03-02
  • 2019-02-22
  • 2017-08-09
  • 2018-07-11
  • 2021-03-13
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多