「Vue.js」v-on:keypressでkeypressイベントを取得する
環境
Windows10 home 64bit
Vue.js 3.2.2
Google Chrome 99.0.4844.51
書式
<input v-on:keypress=イベント名 type="text">
methods: {
イベント名: function (e) {
this.val = "you input: "+e.target.value
}
}
<input v-on:keypress=イベント名 type="text">
methods: {
イベント名: function (e) {
this.val = "you input: "+e.target.value
}
}
<input v-on:keypress=イベント名 type="text"> methods: { イベント名: function (e) { this.val = "you input: "+e.target.value } }
「v-on:keypress」を使用して、keypressイベントを取得します。
使用例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title> keypressイベントサンプル</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app" >
<h2>{{val}}</h2>
name: <input v-on:keypress="cft" type="text">
</div>
<script>
const ark = {
data() {
return {
val: ''
}
},
methods: {
cft: function (e) {
this.val = "you input: "+e.target.value
}
}
}
Vue.createApp(ark).mount('#app')
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title> keypressイベントサンプル</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app" >
<h2>{{val}}</h2>
name: <input v-on:keypress="cft" type="text">
</div>
<script>
const ark = {
data() {
return {
val: ''
}
},
methods: {
cft: function (e) {
this.val = "you input: "+e.target.value
}
}
}
Vue.createApp(ark).mount('#app')
</script>
</body>
</html>
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title> keypressイベントサンプル</title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app" > <h2>{{val}}</h2> name: <input v-on:keypress="cft" type="text"> </div> <script> const ark = { data() { return { val: '' } }, methods: { cft: function (e) { this.val = "you input: "+e.target.value } } } Vue.createApp(ark).mount('#app') </script> </body> </html>
実行結果
テキストフォームに「tokyo」を入力し、keypressイベントが発生し、「you input: toky」文字を表示します。