demo.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<todo>
<todo-title slot="mytodo-title" v-bind:title="booktitle"></todo-title>
<todo-items slot="mytodo-items" v-for="(todoitem,index) in todoitems"
v-bind:item="todoitem" v-bind:bookindex="index" v-on:remove="removeItems(index)" ></todo-items>
</todo>
</div>
<script src="https://cdn.staticfile.org/vue/2.5.21/vue.min.js"></script>
<script>
//slot插槽
Vue.component("todo",{
template: '<div>\
<slot name="mytodo-title"></slot>\
<ul>\
<slot name="mytodo-items"></slot>\
</ul>\
</div>'
});
Vue.component("todo-title",{
props:['title'],
template: '<div>{{title}}</div>'
});
Vue.component("todo-items",{
props:['item','index'],
template: '<li>{{item}} <button @click="removeNode">删除</button></li>',
methods:{
//template只能调到组件内的方法
removeNode:function (index) {
//触发绑定事件
this.$emit('remove',index);
// vm.removeItems(index);也可以
}
}
});
var vm = new Vue({
el: "#app",
data:{
booktitle:"新疆大学的书",
todoitems:['Java书籍','python书籍',"go书籍"]
},
methods: {
removeItems:function (index) {
//数组删除函数
this.todoitems.splice(index,1);
}
}
});
</script>
</body>
</html>
效果: