vue2.0使用slot插槽分发内容

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<father></father>
</div>
<script>
//1
// Vue.component(
// 'my-component',{
// template:`
// <div>
// <slot>
// 只有在没有要分发的内容时才会显示。
// </slot>
// <h2>我是子组件的标题</h2>
// </div>`
// }
// )
// var app = new Vue({
// data:'',
// components:{
// 'father':{
// template:`<div>
// <h1>我是父组件的标题</h1>
// <my-component>
// <p>这是一些初始内容</p>
// <p>这是更多的初始内容</p>
// </my-component>
// </div> `
// }

// }
// }).$mount('#app');
//自组建标记中本来不应该写入值,但加入slot后,父组件中在子组件写的标记会写入slot中。如果去掉slot则不会显示初始内容和更多内容


//2具名插槽
// Vue.component(
// 'my-component',{
// template:`
// <div class="container">
// <header>
// <slot name="header"></slot>
// </header>
// <main>
// <slot></slot>
// </main>
// <footer>
// <slot name="footer"></slot>
// </footer>
// </div>`
// }
// )

// var app = new Vue({
// data:'',
// components:{
// 'father':{
// template:
// `<my-component>
// <h1 slot="header">这里可能是一个页面标题</h1>
// <p>主要内容的一个段落。</p>
// <p>另一个主要段落。</p>
// <p slot="footer">这里有一些联系信息</p>
// </my-component>`
// }

// }
// }).$mount('#app');

//3作用域插槽
Vue.component(
'my-component',{
template:`
<div class="child">
<slot text="hello from child" css="abc"></slot><div>您好</div>
</div>`
}
)

var app = new Vue({
data:'',
components:{
'father':{
template:
`<div class="parent">
<my-component>
<template slot-scope="props">
<span>hello from parent</span>
<span>{{ props.text }}{{ props.css }}</span>
</template>
</my-component>
</div>`
}

}
}).$mount('#app');

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

原文地址:https://www.cnblogs.com/qdcnbj/p/8259372.html