(1). Event
Vue中”子组件”与”父组件通信”,可以通过Event($emit发送事件)来实现.
(2). event.html
<html>
<head>
<title>hello</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 使用组件 -->
<todo>
<todo-title slot="todo-title" v-bind:title="title"></todo-title>
<!-- 3.todo-items组件绑定了一个事件(remove),会触发:removeItems方法 -->
<todo-items slot="todo-items" v-for="(item,index) in items" v-bind:item="item" v-bind:index="index" v-on:remove="removeItems"></todo-items>
</todo>
</div>
<script>
Vue.component('todo-title', {
props:['title'],
template: '<div></div>'
});
Vue.component('todo-items', {
props:['item','index'],
template: '<li> <button @click="remove(index);">删除</button> </li>',
methods:{
// 1. 给子组件绑定事件
remove:function(index){
// 2. $emit发送一件事件(remove)到<todo-items组件上>
this.$emit("remove",index);
}
}
});
Vue.component('todo', {
template: '<div><slot name="todo-title"></slot><ul><slot name="todo-items"></slot></ul></div>'
});
var app = new Vue({
el: '#app',
data : {
title : "用户管理",
items : [ "添加用户","修改用户","删除用户" ]
},
methods : {
// 4. removeItems
removeItems:function(index){
this.items.splice(index,1);
}
}
});
</script>
</body>
</html>