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(...)
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With