9

I have a functionality (getAllData which does an external data query) which I need to call at two occasions: when the component is mounted and when a prop changes.

I am however getting a TypeError: this.getAllData is not a function when using it in a watch and in mounted.

Since methods can be called from methods, I am wondering whether this is true for methods being called from components such as watch or mounted.

My (simplified) instance is below:

export default {
    props: ['triggerReload'],
    data: function () {
        return {
            // some variables
        }
    },
    watch: {
        triggerReload: this.getAllData()
    },
    methods: {
        getAllData: function () {
            // this function correctly fetches external data
        }
    },
    mounted: this.getAllData()
}

My workaround will be to either duplicate the code of the function (which is not DRY) or to call an external function (defined outside the Vue instance - which is probably also an anti-pattern) EDIT: this is a component so I do not know how to call an external function and reference the instance (it is not instantiated by var vm = new Vue(...))

WoJ
  • 27,165
  • 48
  • 180
  • 345

1 Answers1

15

Yes you can, you just have the wrong syntax, you need (note the extra parenthesis):

...
mounted () {
    this.getAllData()
}

which is just ES6 sugar for

mounted: function mounted () {
    this.getAllData()
}

In your version you're binding mounted to this.getAllData when creating the object component, so this will refer to the current object, which does not have a getAllData method. You need to do it in a function instead so Vue can do its magic and bind this to the correct Vue component.

Seb D.
  • 5,046
  • 1
  • 28
  • 36
  • 3
    This answer would profit tremendously from an example how to actually do it right. – Guntram Blohm May 26 '21 at 12:41
  • Maybe I misunderstand something, but is your second example the working one? If so, then the sentence "which is just ES6 sugar for" is extremely misleading; "sugar" suggests that the two are semantically equivalent so, as the first one is wrong, the second one must be as well. – Guntram Blohm Jun 02 '21 at 21:32
  • The two are correct (and are indeed completely equivalent!). The first one is *not* the code from OP, it's the correct version, I'll clarify what was missing (parentesis) – Seb D. Jun 03 '21 at 07:33
  • Aah, that explains it. Thanks a lot for the clarification! – Guntram Blohm Jun 03 '21 at 20:48