AlexForm
AlexForm

Reputation: 77

How do you return a value from a computed property after it was changed in vuejs

I am trying to return a modified variable value in a computed property in vuejs based on a cookie timer.

The idea is simple, if I don't have the cookie, then set the original value and set another variable that should be a cached value (old value) and display it. When the cookie is active and not expired then show the cached value from before.

Here is the code:

export default {
  name: 'app',
  components: {
    mainContr,
    glasses,
    watches
  },
  data: function() {
    return {
      glassKeys: ['blue', 'white', 'brown', 'yellow', 'black', 'small', 'big', 'medium'],
      watchKeys: ['mechanical', 'moonphase', 'bluehands'],
      glassItem: ''
    }
  },
  computed: {
    glasses: function() {
      var cachedItem,
          initialValue

      if (!this.$cookie.get('stringSuffixs')) {
        initialValue = this.glassKeys[Math.floor(Math.random()*this.glassKeys.length)]
        cachedItem = initialValue
        this.$cookie.set('stringSuffixs', 'Thirty seconds later', { expires: '2m' })
        return initialValue
      } else {
        return cachedItem
      }

    }
  }
}

I think that the main issue is that the variables don't get hoisted to the immediate parent function that in my case is the computed property?

Upvotes: 0

Views: 1085

Answers (1)

Roy J
Roy J

Reputation: 43881

Your cachedItem is a local variable that is re-created each time the computed is evaluated. If you want a more persistent cachedItem, you will want to declare it as a data item and use it as this.cachedItem.

Are you sure you don't want a method instead of a computed? Side effects (setting a cookie) and random values don't really belong in computeds.

Upvotes: 1

Related Questions