user11982170
user11982170

Reputation:

How to detect ctrl + z and ctrl + y in vuejs?

Hi I am new to vuejs and currently working on an application which requires the method to be called on Ctrl + z and Ctrl + y. This is what I have tried till now

https://codesandbox.io/s/funny-sky-mqdg0?file=/src/components/HelloWorld.vue

Problem: keyup works only when I ctrl+z is pressed over the input, how do I make it work on div container or make it work on the particular page? is it possible in pure vuejs or i need to install any external library or use traditional event listener way? any suggestions would be helpful

<input @keyup.ctrl.90="method1()" />
<input @keyup.ctrl.89="method2()" />

Upvotes: 4

Views: 3095

Answers (1)

AlekseyHoffman
AlekseyHoffman

Reputation: 2694

You could set up a keyup handler for the whole page.

If you want to undo / redo data outside of an input, I think you have to save each change somewhere and then undo / redo it in the keyup handler.

<div>{{ output }}</div>
data () {
  return {
    changes: [],
    output: ''
  }
},
mounted () {
  document.addEventListener('keyup', this.keyupHandler)
},
destroyed () {
  document.removeEventListener('keyup', this.keyupHandler)
},
methods: {
  logChange (string) {
    this.changes.push(string)
  }
  keyupHandler (event) {
    if (event.ctrlKey && event.key === 'z') {
      this.undoHandler()
    }
    else if (event.ctrlKey && event.key === 'y') {
      this.redoHandler()
    }
  },
  undoHandler () {
    // Get the data from "this.changes" and set the output
    this.output = ...
  },
  redoHandler () {
    // Get the data from "this.changes" and set the output
    this.output = ...
  }
}

Upvotes: 4

Related Questions