<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>-->
<script src="../js/vue.min.js"></script>
</head>
<body>
<!-- view -->
<div id="app">
<todo>
<todo-title slot="todo-title" :title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in items"
:item="item" :key="index" :index="index"
v-on:remove-data="removeItems(index)"></todo-items>
</todo>
</div>
<script>
// slot插槽
Vue.component("todo", {
template: '<div>\
<slot name="todo-title"></slot>\
<ul>\
<slot name="todo-items"></slot>\
</ul>\
</div>'
});
Vue.component("todo-title", {
props: ['title'],
template: '<div>{{title}}</div>'
});
Vue.component("todo-items", {
props: ['item', 'index'],
template: '<li>{{index+1}}--{{item}} <button @click="remove">删除</button></li>',
methods: {
remove: function (index) {
// 自定义事件分发给remove-data事件(注意$emit不支持分发给驼峰命名的事件)
this.$emit('remove-data', index);
}
}
});
var vm = new Vue({
el: '#app',
data: {
title: '我的slot学习!',
items: ['我是大神', '我是大牛', '我是超人']
},
methods: {
removeItems: function(index) {
// 删除items下标index位置开始1个元素
this.items.splice(index, 1);
}
}
})
</script>
</body>
</html>
vue练习demo9-slot
最新推荐文章于 2024-04-01 09:42:47 发布
本文通过一个具体的Vue.js代码示例,详细介绍了如何使用组件、插槽以及自定义事件进行父子组件之间的通信。展示了如何在`todo`组件中传递数据到子组件`todo-title`和`todo-items`,以及子组件如何触发事件来更新父组件的数据。内容涵盖了Vue.js的基础知识,包括组件模板、属性传递、事件监听等。
732

被折叠的 条评论
为什么被折叠?



