vue.jsのスクリプトでボタンを押した数をボタンに表示させ、さらに全ボタンのトータルカウントを上部に表示するサンプルを作成してみました。
https://nakagawach.tokyo/myvue/vue2/
(function(){
'use strict';
// two way data binding(to UI)
var likeComponent = Vue.extend({
props: {
message:{
type: String,
default: 'Like'
}
},
data: function(){
return{
count: 0
}
},
template: '<button @click="countUp">{{ message }} {{ count }}</button>',
methods: {
countUp: function(){
this.count++;
this.$emit('increment');
}
}
});
var app = new Vue({
el: '#app',
components:{
'like-component': likeComponent
},
data: {
total: 0
},
methods: {
incrementTotal: function(){
this.total++;
}
}
});
})();
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>My Vue App</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div id="app">
<p>Total Likes: {{ total }}</p>
<like-component message="Like" @increment="incrementTotal"></like-component>
<like-component message="Awesome" @increment="incrementTotal"></like-component>
<like-component message="Great" @increment="incrementTotal"></like-component>
<like-component @increment="incrementTotal"></like-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="js/main.js"></script>
</body>
</html>
vue.jsでは独自のhtmlタグを定義でき、同時にスクリプトを実行できます。またテンプレートとして定義し簡単に設定できます。
今回は<like-component>というタグをmain.jsで定義し、クリックでcountup関数を実施するボタンオブジェクトを定義し、さらに同時にincrementTotal関数も実行しています。
このように組み込みで関数を定義し実行でき、かなりすっきりしたコードとなっています。
コメント