Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function from watch?

Tags:

vue.js

data: function ()  {     return {        questions: []     } },  watch: {     questions : function(val, oldVal) {         foo()     } },        methods: {     foo() {         console.log("foo called");     } } 

Produce error: ReferenceError: foo is not defined

Also I am looking at examples: http://vuejs-ru.github.io/vuejs.org/api/options.html#watch

What this string do?

handler: function (val, oldVal) { /* ... */ }, handler it's keyword? Or it can be function?

like image 392
Dmitry Bubnenkov Avatar asked Mar 02 '16 18:03

Dmitry Bubnenkov


People also ask

How do you call a function on a Vue watch?

To answer your question about handler : It is a keyword property that can take either a function expression (as in the example) or a reference to a function, such as: function myHandler() { ... } // Defined somewhere outside of the vue component object ... handler: myHandler, ...

How do you trigger a watch in Vue?

To trigger the Vue watch method, you should assign a new city name to the value property of the ref object.

How do you call a Vue phone mount?

The `mounted()` Hook in VueVue calls the mounted() hook when your component is added to the DOM. It is most often used to send an HTTP request to fetch data that the component will then render. For example, the below Vue component uses the mounted() hook to make an HTTP request to the JSONPlaceholder API.

How watch works Vue JS?

A Watcher in Vue. js is a special feature that allows one to watch a component and perform specified actions when the value of the component changes. It is a more generic way to observe and react to data changes in the Vue instance. Watchers are the most useful when used to perform asynchronous operations.


1 Answers

If you want to use watch to observe your property, you could call your method it with this.foo:

data: function ()  {     return {        questions: []     } },      watch: {    questions: {        handler: function(val, oldVal) {            this.foo(); // call it in the context of your component object        },        deep: true     } },            methods: {     foo() {         console.log("foo called");     } } 

To answer your question about handler: It is a keyword property that can take either a function expression (as in the example) or a reference to a function, such as:

function myHandler() { ... } // Defined somewhere outside of the vue component object      ...      handler: myHandler,      ... 

Just out of curiosity: Do you need to watch a property in order to do something every time it changes or could computed properties solve your problem as well?

like image 140
nils Avatar answered Nov 01 '22 09:11

nils