KingKongFrog
KingKongFrog

Reputation: 14419

Computed property that tracks external variable in vue.js not updating

I have a computed property - playerId that is referencing an external object that is not updating.

For example:

var player = require('players');
computed: {
    playerId: function() {
         return player.id
    }
}

If I run this call in a click event it outputs the correct ID. However when this gets updated - computed on its own doesn't update. How do I get this to work? Or am I going about this incorrectly?

Upvotes: 3

Views: 2324

Answers (1)

IzumiSy
IzumiSy

Reputation: 1528

Computed Property in Vue.js does not get reactive with the data which doesn't have any reactive dependecy. For example, the code below would not be updated in each time, because Date.now() has no reactive dependency. The result of this computed value gets cached and it always returns the same value as the one returned at the first time.

computed: {
  now: function () {
    return Date.now()
  }
}

Then, you probably would like to know how to make your external object reactive. The point is, you better put your object into data section in order to track the change of it with Vue's internal watcher. If your computed property has even one a reactive dependency such referencing data or calling method, it is notified every time the dependency get updated and the content returned from the computed property is going to be updated as well.

https://v2.vuejs.org/v2/guide/computed.html

Upvotes: 3

Related Questions