1.插槽slot
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<div id="app"><!-- <p>列表书籍</p>-->
<!-- <ul>-->
<!-- <li>Java</li>-->
<!-- <li>Linux</li>-->
<!-- <li>Python</li>-->
<!-- </ul>--><todo>//todo里面的内容会替代todo里的slot部分,div里面的slot属性代表插到具体name的slot,起名有点让小白蒙蔽,这同样是为什么一开始显示两遍的原理,希望帮到各位。<todo-title slot="todo-title" :title="title"></todo-title><todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items></todo></div><!-- 1.导入Vue.js -->
<script src="../js/vue.js"></script>
<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'],template: '<li>{{item}}</li>'});var vm = new Vue({el:"#app",data:{title:'秦老师列表',todoItems: ['狂神说Java','狂神说前端','狂神说Linux']}});</script></body>
</html>
2.自定义事件
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<div id="app"><!-- <p>列表书籍</p>-->
<!-- <ul>-->
<!-- <li>Java</li>-->
<!-- <li>Linux</li>-->
<!-- <li>Python</li>-->
<!-- </ul>--><todo>//todo里面的内容会替代todo里的slot部分,div里面的slot属性代表插到具体name的slot,起名有点让小白蒙蔽,这同样是为什么一开始显示两遍的原理,希望帮到各位。<todo-title slot="todo-title" :title="title"></todo-title><todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:index="index" :item="item" v-on:remove="removeItems(index)"></todo-items></todo></div><!-- 1.导入Vue.js -->
<script src="../js/vue.js"></script>
<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}}-------{{item}}<button @click="remove">删除</button></li>',methods: {remove: function (index) {this.$emit('remove',index)}}});var vm = new Vue({el:"#app",data:{title:'秦老师列表',todoItems: ['狂神说Java','狂神说前端','狂神说Linux']},methods: {removeItems:function (index){console.log("删除了"+index+'号元素,元素名为'+this.todoItems[index])this.todoItems.splice(index,1);}}});</script></body>
</html>