WoJ
WoJ

Reputation: 30035

How to reassess a computed value upon key press?

I would like to display a different random word from a list upon pressing a key.

The "displaying a random word" part works fine:

var vm = new Vue({
  el: "#root",
  data: {
    verbs: ['parier', 'coûter', 'couper', 'blesser']
  },
  computed: {
    verb: function() {
      return this.verbs[Math.floor(Math.random() * this.verbs.length)];
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="root">
  {{verb}}
</div>

I now would like to bind a keypress to the re-computation of verb. How should I do that?

The documentation on event handling suggests using v-on:keydown for this - I can add JavaScript (v-on:keydown="alert()" for instance) but do not know how to trigger a recalculation of a value (I tried v-on:keydown="eval(verb)" but it did not work).

Upvotes: 1

Views: 490

Answers (1)

David L
David L

Reputation: 33853

Computed values by design are ideally run once.

One solution mentioned by Vue's creator, Evan, was to attach a global listener on component creation, and then call your method directly.

var vm = new Vue({
  el: "#root",
  data: {
    verb: '',
    verbs: ['parier', 'coûter', 'couper', 'blesser']
  },
  methods: {
    getRandomVerb: function() {
      this.verb = this.verbs[Math.floor(Math.random() * this.verbs.length)];
    }
  },
  mounted() {
      window.addEventListener('keydown', this.getRandomVerb)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="root">
  {{verb}}
</div>

To get the demo to respond correctly, Run the code snippet, then click in the snippet window and begin typing. Random verbs will be displayed.

Upvotes: 1

Related Questions