vue 使用插槽分发内容操作示例【单个插槽、具名插槽、作用域插

2020-06-16 06:56:05易采站长站整理

<p slot="footer">这里有一些联系信息</p>
</app-layout>
</div>
<script>
Vue.component('app-layout',{
template:'<div class="container">'+
'<header>'+
'<slot name="header"></slot>'+
'</header>'+
'<main>'+
'<slot></slot>'+
'</main>'+
'<footer>'+
'<slot name="footer"></slot>'+
'</footer>'+
'</div>'
})

// 创建根实例
new Vue({
el: '#example',

})
</script>
</body>
</html>

作用域插槽

作用域插槽是一种特殊类型的插槽,用作一个 (能被传递数据的) 可重用模板,来代替已经渲染好的元素。

在子组件中,只需将数据传递到插槽,就像你将 prop 传递给组件一样:


<div class="child">
<slot text="hello from child"></slot>
</div>

在父级中,具有特殊特性 slot-scope 的 <template> 元素必须存在,表示它是作用域插槽的模板。slot-scope 的值将被用作一个临时变量名,此变量接收从子组件传递过来的 prop 对象:

在 2.5.0+,slot-scope 能被用在任意元素或组件中而不再局限于 <template>。


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 作用域插槽</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
</head>
<body>

<div id="example">
<parent-com></parent-com>
</div>
<script>
Vue.component('child-com',{
template:'' +
'<ul>' +
' <slot name="child-ul" v-for="item in animal" v-bind:text="item.name"></slot>' +
'</ul>',
data:function(){
return {
animal:[
{name:'大象'},
{name:'小狗'},
{name:'小猫'},
{name:'老虎'}
] }
}
});
//父组件
// 在父组件的模板里,使用一个Vue自带的特殊组件<template> ,
// 并在该组件上使用scope属性,值是一个临时的变量,存着的是由子组件传过来的
// prop对象,在下面的例子中我把他命名为props。
// 获得由子传过来的prop对象。这时候,父组件就可以访问子组件在自定义属性上暴露的数据了。
Vue.component('parent-com',{
template:'' +
'<div class="container">' +
'<p>动物列表</p>' +
'<child-com>' +