代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in todoItems" :item="item" :index="index"
v-on:remove="removeItem(index)"></todo-items>
</todo>
</div>
<script>
Vue.component("todo", {
template: '<div>\n' +
' <slot name="todo-title"></slot>\n' +
' <ul>\n' +
' <slot name="todo-items"></slot>\n' +
' </ul>\n' +
'</div>'
});
Vue.component("todo-title", {
props: ['title'],
template: '<div>{
{title}}</div>'
});
Vue.component("todo-items", {
props: ['item', 'index'],
template: '<li>{
{item}} <button @click="remove">删除</button></li>',
methods: {
remove: function (index) {
this.$emit('remove', index);
}
}
});
var vm = new Vue({
el: '#app',
data: {
title: 'jyuxuan',
todoItems: ['Java', 'JavaWeb', 'JavaEE']
},
methods: {
removeItem(index) {
this.todoItems.splice(index, 1);
}
}
})
</script>
</body>
</html>