Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a computed property from a method in a Single File Component with Vue.js

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.

like image 513
andcl Avatar asked Sep 19 '18 17:09

andcl


People also ask

How do I use computed property in Vue?

In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.


1 Answers

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

like image 129
moritz.vieli Avatar answered Oct 13 '22 03:10

moritz.vieli