[TOC]
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>
```
## 思路步骤
### 1.先生成一个组件 将组件放入html页面中
```
<div id="app"></div>
Vue.component('like',{
template:'<button>👍2</button>'
})
new Vue({
el:'#app'
)}
// div中加入
<like></like>
```
### 2. 建立一个data 存储点赞数
```
data: function(){
return{
like_count:10,
}
}
//相应的button改为
<button >👍{{like_count}}</button>
```
### 3.增加点击事件 @click="toggle_like"
```
<button @click="toggle_like" >👍{{like_count}}</button>
//组里增加点击事件的方法
methods:{
toggle_like:function(){
this.like_count++
}
}
```
### 4.给点击事件增加一个条件
```
data:function(){
return{
like_count:10,
liked:false,
}
}
toggle_like:function(){
//如果点赞就是liked为true
if(!this.liked){
this.like_count++
}else{
this.like_count--
}
this.liked=!this.liked
}
```
### 5.增加一个样式 确定已点赞
```
:class='{like:liked}' if / liked为真添加like 为假除去like样式
```
### 6.将组件用template标签存放在html里 优化代码
```
<template id="like-component">
<button @click="toggle_like">👍{{like_count}}</button>
</template>
//Vue.component
template:'#like-component'
```
## 代码块
```
<div id="app">
<like></like>
</div>
<script>
Vue.component('like', {
template: '<button @click="toggle_like()" :class="{like:liked}">👍{{like_count}}</button>',
data: function () {
return {
like_count: 10,
liked: false
}
},
methods: {
toggle_like: function () {
if(!this.liked){
this.like_count++;
}else{
this.like_count--;
}
this.liked=!this.liked
}
}
})
new Vue({
el: '#app',
})
</script>
```
## 优化代码块
```
<div id="app">
<like></like>
</div>
<template id="like-component">
<button @click="toggle_like()" :class="{like:liked}">👍{{like_count}}</button>
</template>
<script>
Vue.component('like', {
template: '#like-component',
data: function () {
return {
like_count: 10,
liked: false
}
},
methods: {
toggle_like: function () {
if(!this.liked){
this.like_count++;
}else{
this.like_count--;
}
this.liked=!this.liked
}
}
})
new Vue({
el: '#app',
})
</script>
```