自定义事件+内容分发
本文仅仅为本人学习vue的简易笔记,内容不严谨,有瑕疵,请慎重浏览
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<todo>
<todo-title slot="todo-title" v-bind:title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in ItemsList" v-bind:item="item" v-bind:index="index" v-on:remove="removeItems(index)"></todo-items>
</todo>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<script type="text/javascript">
//slot 插槽
Vue.component("todo",{
template: "<div>\n" +
"<slot name='todo-title'></slot>"+
" <ul>\n" +
" <slot name='todo-items'></slot>" +
" </ul>\n" +
"</div>"
});
Vue.component("todo-title",{
props: ['title'],
template: "<div>{{title}}</div>"
});
Vue.component("todo-items",{
props: ['item','index'],
//只能绑定当前组件的方法
template: "<li>{{index}}----{{item}} <button v-on:click='remove'>删除</button></li>",
methods: {
remove: function (index) {
this.$emit('remove',index)
alert("删除成功")
}
}
})
var vm = new Vue({
el:'#app',
data: {
title: "列表",
ItemsList: ["Java", "Web", "Python"]
},
methods: {
removeItems: function (index) {
//一次删除一个元素
this.ItemsList.splice(index,1);
}
}
});
</script>
</body>
</html>
效果图: