爲了更好的理解之前的各類知識,認真的實現下面的demo很有必要。。。
就是當點擊“掉血”按鈕後,進度條的血減10%,然後一直點到0的時候圖片就會變成另外一張打壞了的圖片。。
事例代碼如下,圖片可以隨便兩張吧,簡單實現
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Vue 測試實例 </title>
<!--通過cdn的方式加載入vue文件-->
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<style type="text/css">
#bag{
width: 200px;
height: 500px;
margin: 0 auto;
background: url(img/bag.png) center no-repeat;
background-size: 80%;
}
#bag.burst{
background-image: url(img/bag-burst.png);
}
#bag-health{
width: 200px;
border: 2px solid #000;
margin: 0 auto 20px auto;
}
#bag-health div{
height: 20px;
background: crimson;
}
#controls{
width: 200px;
margin: 0 auto;
}
#controls button{
margin-left: 10px;
}
</style>
</head>
<body>
<div id="app">
<!--圖片 當血條爲0的時候變圖片-->
<div id="bag" v-bind:class="{burst:ended}"></div>
<!--進度情況 讓血條的百分比和health同步-->
<div id="bag-health">
<div v-bind:style="{width:health+'%'}"></div>
</div>
<!--控制按鈕-->
<div id="controls">
<!--執行punch方法,每次觸發數值減10-->
<button v-on:click="punch" v-show="!ended">使進度條掉血</button>
<!--執行restart方法,恢復原樣-->
<button v-on:click="restart">重新開始</button>
</div>
</div>
<script>
//實例化vue對象
new Vue({
el: '#app', //element 獲取元素
data: { //用於數據的存儲
health:100, //定義血條
ended:false
},
methods:{ //用於各種方法的定義
punch:function(){
this.health-=10;
if(this.health<=0){
this.ended=true;
}
},
restart:function(){
this.health=100;
this.ended=false;
}
}
});
</script>
</body>
</html>