Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger a watch function whenever any variable is changed in Vue.js

Is there a way I can trigger a Vue.js function whenever a variable within the app changed?

var vm = new Vue({
  el: '#demo',
  data: {
    variable1: 'Foo',
    variable2: 'Bar',
    .....
    .....
    variablen: 'Foo Bar'
  },
  watch: {
    <<any variable>>: function(){
      console.log('any of these variables changed');
    }
  }
})
like image 393
Ishan Madhusanka Avatar asked Feb 09 '17 16:02

Ishan Madhusanka


People also ask

How do I watch data changes on Vue instance?

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.

How do you use the watch function in Vue Cinema?

The Vue. js Watcher or watch property allows the developers to listen to the component data and run whenever they change a particular property. The watcher or watch property is a unique Vue. js feature that lets you keep an eye on one property of the component state and run a function when that property value changes.

What is the difference between watch and computed in Vuejs?

Computed props can react to changes in multiple props, whereas watched props can only watch one at a time. Computed props are cached, so they only recalculate when things change. Watched props are executed every time.

Can you watch a computed property Vue?

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


1 Answers

First of all, I agree with all comments saying that 50 fields sound like a code smell and that code probably need to be refactored.

Beside that, vue allows you to watch for whole data object using $data watch and explicitly set it as deep

  watch: {
    '$data': {
      handler: function(newValue) {
        console.log('Current vaules:' + newValue.FirstName + ' ' + newValue.LastName);
      },
      deep: true
    }
  }

Please see this working fiddle and this watch documentation extract

Option: deep

To also detect nested value changes inside Objects, you need to pass in deep: true in the options argument. Note that you don’t need to do so to listen for Array mutations.

Warning

As @BelminBedak remarks, this example only demonstrates that it is possible to archive but not recommended for production environments.

like image 100
AldoRomo88 Avatar answered Sep 30 '22 05:09

AldoRomo88