Show keyCode of Pressed Key via Go and Vue.js
Example for getting keyCode of pressed key of focused HTML input element via gopherjs-vue.
See the following the HTML code:
HTML
<div id="vueapp">
<input type="text" @keyup="ShowKeyCode" placeholder="Press Any Key Here" />
<div>The keyCode of the keypress: {{ keypressed }}</div>
</div>
When the input element is focused and user press some key, the keyCode of the pressed key will be shown below the input element.
The following is the Go code for above HTML code:
Go
package main
import (
"github.com/gopherjs/gopherjs/js"
"github.com/oskca/gopherjs-vue"
)
type Model struct {
*js.Object // this is needed for bidirectional data bindings
Keypressed string `js:"keypressed"`
}
// this would be recognized as Show in html
func (m *Model) ShowKeyCode(event *js.Object) {
m.Keypressed = event.Get("keyCode").String()
}
func main() {
m := &Model{
Object: js.Global.Get("Object").New(),
}
// field assignment is required in this way to make data passing works
m.Keypressed = ""
// create the VueJS viewModel using a struct pointer
vue.New("#vueapp", m)
}
The above Go code is equivalent to the following JavaScript code:
JavaScript
'use strict';
new Vue({
el: '#vueapp',
data: {
keypressed: ""
},
methods: {
ShowKeyCode: function (event) {
this.keypressed = event.keyCode;
}
}
});
The full code example can be found on my GitHub.
References:
[1] | [Vue.js] Keyboard Event (Arrow Key Example) |