Vue2-Slot插槽使用

Slot插槽

  • 父组件向子组件传递
  • 父组件将内容分发到子组件
  • slot插槽的值只读,不能在子组件中修改
  • slot插槽也可以作为组件之间的通信方式

默认插槽

父组件中:使用Son组件
    <template>
        <Son>
           <ul> //子组件如果不定义插槽 这里面的ul不起作用
    	    <li></li>
	    <li></li>
	    <li></li>
   	   </ul>
        </Son>
    </template>

子组件中:
    <template>
        <div>
         <!-- 定义插槽 -->
           <slot>父组件中没有内容就显示这句话...</slot>
         </div>
     </template>

具名插槽

#两种方式
`注意 v-slot:简写为 # 且 具名插槽需要用 template 包裹(组件不用 template 包裹)`
父组件中:使用Son组件  
  <template>
	<Son>
   	<h1 slot="demo1">迷死他<h2>
        <ul slot="demo2"> 
    	  <li></li>
          <li></li>
 	  <li></li>
   	 </ul>
        </Son>     
  </template>
//第二种写法 必须要加上template标签
        <template v-slot:demo2>
          <ul> 
                <li></li>
                <li></li>
                <li></li>
   	  </ul>
        </template>

子组件中:
        <template>
            <div>
               <!-- 定义插槽 -->
               <slot name="demo1">父组件中没有内容就显示这句话...</slot>
	       <slot name="demo2">父组件中没有内容就显示这句话...</slot>
            </div>
        </template>

作用域插槽

#数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(son组件在father组件中使用,但是数据来源是Son组件本身,这时就需要在Son组件中用作用域插槽将数据传输给插槽的使用者)
`父组件中:`
方法一:
	<Son>
		<template scope="formSon"> 
		<!-- dataSource来子组件  -->
			<ul>
				<li v-for="(k,index) in dataSource" :key="index">{{k}}</li>
			</ul>
		</template>
	</Son>
方法二:
	<Son>//第二种写法
		<template slot-scope="formSon">
			<!-- 生成的是h4标题 -->
			<h4 v-for="(k,index) in dataSource" :key="index">{{k}}</h4>
		</template>
	</Son>

`子组件中:`
    <template>
        <div>
            <slot :dataSource="dataSource"></slot>
        </div>
    </template>  
	<script>
        export default {
            //数据在子组件自身
            data() {
                return {
                   dataSource:['lht','lht1','lht2','lht3']
                }
            },
        }       
    </script>            

应用场景示例

template中的插槽---具名插槽

#父组件中:father.vue
	#导入子组件
import Son from './son.vue'    
<template>
  <Son>
    <template v-slot:www>
        <div>......</div> 
      //div中可以用来取父组件的值,存放到插槽再分发给子组件
    </template>
  </Son>
</template>    

#子组件中 son.vue 使用父组件中的插槽
<slot name="www"></slot>
//渲染后就出现父组件的结构内容
posted @   残星落影  阅读(674)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
欢迎阅读『Vue2-Slot插槽使用』
点击右上角即可分享
微信分享提示