<div id="app">
<div class="container">
<div-cast></div-cast>
</div>
</div>
<script type="text/javascript" src="../node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
var costtitle = {
props: ["uname"],
template: `
<div class="title">{{uname}}的商品</div>
`,
}
var costlist = {
props: ["list"],
template: `
<div>
<div class="item" :key="item.id" v-for="item in list">
<img :src="item.img" />
<div class="name">{{item.name}}</div>
<div class="change">
<a href="" @click.prevent="sub(item.id)">-</a> //子传父
<input type="text" class="num" v-model="item.num"/>
<a href="" @click.prevent="add(item.id)">+</a> //子传父
</div>
<div class="del" @click="dele(item.id)">×</div>
</div>
</div>
`,
methods: {
sub: function (id) {
this.$emit("div-con", {
id: id, //
},
add: function (id) {
type: "sub"
}) this.$emit("div-con", { //
},
dele:function(id){
// 根据id删除
//找到索引
var index = this.list.findIndex(item => {
return item.id == id
})
this.list.splice(index,1)
}
}
}
id: id,
type: "add"
})var costfoot = {
props: ["list"],
template: `
<div class="total">
<span>总价:{{total}}</span>
<button>结算</button>
</div>
`,
computed: {
total: function () {
var numb = 0;
this.list.forEach(item => {
numb += item.price * item.num;
})
return numb;
}
}
}
Vue.component("div-cast", {
data: function () {
return {
uname: '张三',
list: [{
id: 1,
name: 'TCL彩电',
price: 1000,
num: 1,
img: './img/a.jpg'
}, {
id: 2,
name: '机顶盒',
price: 1000,
num: 1,
img: './img/b.jpg'
}, {
id: 3,
name: '海尔冰箱',
price: 1000,
num: 1,
img: './img/c.jpg'
}, {
id: 4,
name: '小米手机',
price: 1000,
num: 1,
img: './img/d.jpg'
}, {
id: 5,
name: 'PPTV电视',
price: 1000,
num: 2,
img: './img/e.jpg'
}]
}
},
template: `
<div class='cart'>
<costtitle :uname = "uname"></costtitle>
<costlist :list = "list" @div-con="handle($event)"></costlist> //父组件用v-on 监听子组件的事件
<costfoot :list = "list"></costfoot>
</div>
`,
components: { //局部组件
"costtitle": costtitle,
"costlist": costlist,
"costfoot": costfoot,
},
methods: {
handle:function(val){
console.log(val);
if(val.type =="sub"){
this.list.some(item => {
if(val.id == item.id){
item.num -= 1;
return true;
}
})
}
else if(val.type == "add"){
this.list.some(item => {
if(val.id == item.id){
item.num += 1;
return true;
}
})
}
}
}
})
var pp = new Vue({
el: "#app",
methods: {
},
})