Vue-slot插槽
应用在组合组件的场景中
<!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> <!-- v-bind简写为一个冒号:-->
<todo-items slot="todo-items" v-for="item in todoItems" v-bind:item="item"></todo-items>
</todo>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
// Vue.component("todo",{
// template: "<div>"+
// "<slot></slot>" +
// "<ul>" +
// "<slot></slot>"+
// "</ul>"+
// "</div>"
// });
Vue.component("todo",{ //反斜杠实现换行,slot插槽
template: "<div>\
<slot name='todo-title'></slot>\
<ul>\
<slot name='todo-items'></slot>\
</ul>\
</div>"
});
Vue.component("todo-title",{ //将数据填充到第一个组件
props:["title"], // 接收参数
template: "<p>{{title}}</p>"
});
Vue.component("todo-items",{
props:["item"],
template:"<li>{{item}}</li>"
});
var vm=new Vue({
el:"#app",
data:{
title:"列表",
todoItems:["C","java","Python"]
}
});
</script>
</body>
</html>
自定义事件分发
组件中也可以定义方法实现参数传递和事件分发: this.$emit('自定义事件名',参数)
<!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> <!-- v-bind简写为一个冒号:-->
<todo-items slot="todo-items" v-for="(item,index) in todoItems"
v-bind:item="item" v-bind:index="index" v-on:remove="removeItems(index)"></todo-items>
</todo>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
// Vue.component("todo",{
// template: "<div>"+
// "<slot></slot>" +
// "<ul>" +
// "<slot></slot>"+
// "</ul>"+
// "</div>"
// });
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: "<p>{{title}}</p>"
});
Vue.component("todo-items",{
props:["item","index"],
template:"<li>{{index}}---{{item}}<button @click='remove'>删除</button></li>", //@是事件的简写(v-on)
methods:{ //只能绑定当前组件的方法
remove: function (index) {
this.$emit("remove",index);
}
}
});
var vm=new Vue({
el:"#app",
data:{
title:"列表",
todoItems:["C","java","Python"]
},
methods: {
removeItems:function (index) {
this.todoItems.splice(index,1) //一次删除一个元素
console.log("删除了"+this.todoItems[index]+"ok")
}
}
});
</script>
</body>
</html>
标签:slot,index,vue,自定义,title,component,Vue,template,todo From: https://www.cnblogs.com/yuanyu610/p/17021229.html