vue.js入門_15_イベントハンドリング
by s9iwork
HTML
<div id="app">
<h2>インラインメソッドハンドラ</h2>
<p>{{counter}}</p>
<button v-on:click="counter++">Click</button>
<h2>メソッドイベントハンドラ</h2>
<h3>引数なし</h3>
<p>{{counter2}}</p>
<button v-on:click="clickHandler">Click2</button>
<h3>引数あり</h3>
<button v-on:click="updateMessage($event, 'fugafuga')">updateMessage</button>
<p>{{message}}</p>
<h3>イベント修飾子</h3>
<button v-on:click="showCurrentDate">showCurrentDate</button>
<p>{{currentDate}}</p>
<button v-on:click.once="showCurrentDate2">showCurrentDate2</button>
<p>{{currentDate2}}</p>
<h3>キー修飾子</h3>
<input type="text" v-on:keyup.esc.space="clearText" v-model="text">
<p>{{text}}</p>
<h3>システム修飾子</h3>
<input type="text" @keyup.ctrl.c="clearText2" v-model="text2">
<p>{{text2}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>
CSS
.large {
font-size: 1.5rem;
}
.small {
font-size: 0.5rem;
}
.text-danger {
color: #F00;
}
.italic {
font-style: italic;
}
h2 {
font-size: 1.2rem;
}
h2::before {
content: "■";
}
JavaScript
new Vue({
el: '#app',
data: {
counter: 0,
counter2: 0,
message: 'hogehoge',
currentDate: '',
currentDate2: '',
text: 'hogehoge',
text2: 'fugafuga',
},
methods: {
clickHandler: function(event) {
this.counter2++
console.log(event.target.tagName)
},
updateMessage: function(event, value) {
this.message = value
console.log(event.target.innerHTML)
},
showCurrentDate: function() {
this.currentDate = new Date().toLocaleTimeString()
},
showCurrentDate2: function() {
this.currentDate2 = new Date().toLocaleTimeString()
},
clearText: function() {
this.text = ''
},
clearText2: function() {
this.text2 = ''
}
}
})