56

I have a normal single file component which has both a computed property and some methods:

<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>

When I try to access this.formattedMatches() from the method, I get a [Vue warn]: Error in render: "TypeError: this.formattedMatches is not a function" .

What is the correct way to achieve what I want? Thanks in advance.

andcl
  • 3,342
  • 7
  • 33
  • 61

2 Answers2

102

You can access computed properties like a property, not like a method:

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

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

Note: If you treat it as a method with paracentesis () it shall throw an error like this Error in v-on handler: "TypeError: this.myProperty is not a function".

Ebrahim
  • 1,740
  • 2
  • 25
  • 31
moritz.vieli
  • 1,747
  • 1
  • 14
  • 17
  • 2
    dang how to know that just property is required tried always as method, thanks –  Aug 27 '20 at 09:51
0

I have given

isWeb: function () {
        return isWebOnly;
      }

in computed properties.

Now I HAVE TO USE isWeb() in the methods section

isQuickViewEnabled (
        { userData }: {userData: AlgoliaUserData[] | undefined }): boolean {
        if (Array.isArray(userData)) {
          const quickViewEnabled = userData[0]?.quick_view_enabled;
          return this.**isWeb** && quickViewEnabled;
        }
        return false;
      },

But its giving Property 'isWeb' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<{ product: any; position: number; results: any; cornerFlagsRules: CornerFlags[]; }>>'.