Vue 子组件调用父组件 $emit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 子组件调用父组件 $emit</title>
</head>
<body>
<div id="app">
<table border="2">
<tr v-for="(item,index) in items">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>
<dsj-numbox v-bind:count="item.count" v-on:genxin="handleUpdate" :index="index"></dsj-numbox>
</td>
</tr>
</table>
<p>总计{{totalCount}} 件商品</p>
</div>
<script src="vue.js"></script>
<!-- //测试数据 -->
<script>
var goods = [
{
id: 1001,
name: "百事可乐",
count: 3
},
{
id: 1002,
name: "红牛",
count: 12
},
{
id: 1003,
name: "乐吧 ",
count: 31
},
{
id: 1004,
name: "乐虎",
count: 2
},
{
id: 1005,
name: "百岁山",
count: 3
}
]
</script>
<template id="template-numbox">
<div>
<button type="button" @click="jian(index)">-</button>
<input type="text" size="2" v-bind:value="count" />
<button type="button" @click="jia(index)">+</button>
</div>
</template>
<!-- 创建组件数字框 -->
<script>
Vue.component("dsj-numbox", {
props: ["index", "count"],
template: "#template-numbox",
methods: {
jia: function(index) {
//emit:调用的是事件,不是方法
//1、父组件可以使用 props 把数据传给子组件。
//2、子组件可以使用 $emit 触发父组件的自定义事件。
this.$emit("genxin", this.index, this.count + 1);
},
jian: function(index) {
this.$emit("genxin", this, index, this.count - 1);
}
}
});
var app = new Vue({
el: "#app",
data: {
items: goods
},
methods: {
//将指定商品数量
handleUpdate: function(index, count) {
this.items[index].count = count;
}
},
computed: {
totalCount: function() {
var sum = 0;
for (var i = 0; i < this.items.length; i++) {
sum += this.items[i].count;
}
return sum;
}
}
})
</script>
</body>
</html>