6

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');
    }
  }
})
6
  • 1
    I don't think this is possible and even if it was I wouldn't recommend it. What's wrong with watching properties individually? Is there something specific you need to do? Maybe there is a simpler solution. Commented Feb 9, 2017 at 16:19
  • Let's say I need to trigger a single function, say to update data from a GET request, whenever any variable is updated. In my case, I have about 50 fields to watch for. Commented Feb 9, 2017 at 16:23
  • 1
    Well probably your data model structure is not the best - you can store all variables in object and then watch whole object and then trigger method. Commented Feb 9, 2017 at 16:28
  • 1
    @BelminBedak suggested the only solution, but even if you take his advice 50+ properties sounds too much... I think you need to restructure your app. If you need this much data to be stored in your data object you might even look into Vuex. Commented Feb 9, 2017 at 16:34
  • Great thoughts guys..Cool! Looks like I'll have to think of a good way to restructure the app. Commented Feb 9, 2017 at 16:39

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Watching whole $data object is least option that he should do.For example is okay, but in real app I won't suggest to do that.
Totally agree with you @BelminBedak, I've just update answer to add that warning, thanks for pointed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.