運用組件添加刪除元素(父給子傳)
父給子傳(用props屬性傳值)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('my-father',{
template:`
<div>
<input type="text" v-model="inputVal"> <button @click='add'>添加</button>
<my-child v-bind:fruit='list'></my-child>
</div>
`,
data:function(){
return{
list:['apple','pear','orange'],
inputVal:''
}
},
methods:{
add:function(){
this.list.push(this.inputVal);
}
}
})
Vue.component('my-child',{
props:['fruit'],
template:`
<ul>
<li v-for="(value,index) in fruit">
{{value}}
<button @click="delt(index)">刪除</button>
</li>
</ul>
`,
methods:{
delt:function(ind){
this.fruit.splice(ind,1)
}
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>

QQ拼音截圖未命名.png
運用組件做購物車效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('my-father',{
template:`
<div class='container'>
<table class='table table-bordered text-center'>
<thead>
<tr>
<th class='text-center'>編號</th>
<th class='text-center'>名稱</th>
<th class='text-center'>單價</th>
<th class='text-center'>數(shù)量</th>
<th class='text-center'>小計</th>
</tr>
</thead>
<my-child v-bind:product='goods'></my-child>
</table>
</div>
`,
data:function(){
return{
goods:[
{pname:'apple',price:3,count:3,sub:9},
{pname:'pear',price:4,count:4,sub:16},
{pname:'orange',price:5,count:5,sub:25}
]
}
}
})
Vue.component('my-child',{
props:['product'],
template:`
<tbody>
<tr v-for="(value,index) in product">
<td>{{index+1}}</td>
<td>{{value.pname}}</td>
<td>{{value.price}}</td>
<td>
<button @click='add(index)'>+</button>
<span>{{value.count}}</span>
<button @click='redu(index)'>-</button>
</td>
<td>{{value.sub}}</td>
</tr>
<tr>
<td colspan=5>總價:{{sum}}</td>
</tr>
</tbody>
`,
data:function(){
return{
sum:""
}
},
methods:{
add:function(ind){
this.product[ind].count++;
//小計、
this.product[ind].sub=this.product[ind].count*this.product[ind].price;
this.countSum();
},
redu:function(ind){
if(this.product[ind].count>1){
this.product[ind].count--;
}
//小計
this.product[ind].sub=this.product[ind].count*this.product[ind].price;
this.countSum();
},
countSum:function(){
for(var i=0,total=0;i<this.product.length;i++){
total+=this.product[i].sub;
}
this.sum=total;
}
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>

QQ拼音截圖未命名.png