2019 年 5 月 29 日 07:51:57
插槽 - 这里之前没怎么注意 这次算是懂了个大概
作用域插槽 应用场景 当子组件循环或者 dom 结构需要外部父子间传递的时候用
必须使用 template 标签 -> slot-scope 接收 ->slot 定义属性传递值给 template 就这三部其实
代码如下
- <!DOCTYPE html>
- <HTML>
- <head>
- <title>
- test for vue
- </title>
- <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js">
- </script>
- </head>
- <body>
- <div id="app">
- <!-- 4-5 -->
- <!-- <h3> 非父子组件间传值 (Bus / 总线 / 发布订阅模式 / 观察者模式)</h3>
- <child content="Dad gives u"></child>
- <child content="This money"></child> -->
- <!-- 4-6/4-7 -->
- <h3>
- 插槽 slot / 作用域插槽
- </h3>
- <child>
- <!-- <h4> 这里是子组件需要插槽的 part</h4> -->
- <div class="header" slot="header">
- Header 网页头
- </div>
- <div class="footer" slot="footer">
- Footer 网页脚
- </div>
- </child>
- <test_for_slot>
- <template slot-scope="SlotData">
- <h2>
- {{SlotData.thisis_shuxing}}
- </h2>
- </template>
- </test_for_slot>
- </div>
- <script type="text/javascript">
- // 4-5
- // // 非父子组件 用总线机制 其实就是给 vue 挂了个全局的属性
- // Vue.prototype.bus = new Vue()
- // Vue.component('child',{
- // props:{
- // content:String
- // },
- // data(){
- // return {
- // selfContent:this.content
- // }
- // },
- // template:'<div @click="handleClick">{{selfContent}}</div>',
- // methods:{
- // handleClick(){
- // // alert(this.content)
- // this.bus.$emit('explode_func',this.selfContent)
- // }
- // },
- // mounted:function(){
- // var _that = this
- // this.bus.$on('explode_func',function(msg){
- // alert(msg) // 这里会跳出两次 以为组件有两个 都监听了方法
- // _that.selfContent = msg
- // })
- // }
- // })
- 4 - 6 Vue.component('child', {
- props: ['content'],
- template: ` < div > <slot name = "header" > <h4 > 如果插没有传值默认显示内容 < /h4>
- </slot > <div > 中间内容 < /div>
- <slot name="footer"></slot > </div>
- `
- })
- Vue.component('test_for_slot',{
- data:function(){
- return {
- list:['a','b','c','d']
- }
- },
- template:`<div>
- <ul>
- <slot v-for="item of list"
- :thisis_shuxing=item
- >
- {{item}}
- </slot > </ul>
- </div > `
- }) var App = new Vue({
- el: "#app"
- })
- </script>
- </body>
- </HTML>
Slot 肯定还有别的使用场景 只是没有讲到 以后项目遇到了再做个总结
下一节是动态组件跟 v-once 指令
来源: http://www.jianshu.com/p/6139b145c1ab