vue2.0与3.0 插槽


theme: channing-cyan

vue2写法

子组件 child

<template>
    <div>
        <slot></slot>
         <slot name="childs"></slot>
         <slot name="childRef" :user="user">{
   
   {user.age}}</slot>
    </div>
</template>
<script>
    export default {
    data() {
        return {
            user: {
                name: '猪小明',
                age: 28
            }
        }
    }
    }
</script>

父组件 app

<template>
    <div id="app">
        <child>
            <div>我是匿名插槽</div>
            <div slot="childs">我是具名插槽</div>
            <div slot-scope="scope" slot="childRef">
                作用域插槽{
   
   {scope.user.name}}
            </div>
        </child>
    </div>
</template>

匿名插槽与具名插槽比较简单

作用域插槽:

在Vue中有渲染作用域的概念:

父级模板里的所有内容都是在父级作用域中编译的;

子模板里的所有内容都是在子作用域中编译的;

在父级模板中是无法访问到子级的内容的,因为它们是跨作用域的访问

这时 通过定义插槽的prop就可以获取到子级的值,然后渲染在父组件

image.png

vue2.6之后添加了v-slot写法,slot-scope依然可以使用 下面是用法

在2.6之前使用的是slot 和 slot-scpe 2.6后已被官方废弃,但在2.x版本仍被支持,

在2.6版本后更新的新指令 v-slot 来替代slot 和slot-scpe v-solt只能是template元素上

2.6后插槽 可以把参数之前的所有内容 (v-slot:) 替换为字符 #。例如 v-slot:child 可以被重写为 #child v-slot:后面必须有值

父组件

<template>
    <div id="app">
        <child>
            <template v-slot><p>我是匿名插槽</p></template>
            <template v-slot:childs>我是具名插槽</template>
            <template v-slot:childRef="{data}">
                作用域插槽{
   
   {data.name}}
            </template>
        </child>
    </div>
</template>

父组件第二种写法

<template>
    <div id="app">
        <child>
             <template #num>我是具名插槽</template>
             <template #childRef="{ data }">
                   作用域插槽{
   
   { data.name }}-{
   
   { data.age }}
             </template>
        </child>
    </div>
</template>
  

子组件

<template>
    <div>
         <slot></slot>
         <slot name="childs"></slot>
         <slot name="childRef" :data="user">{
   
   {user.age}}</slot>
    </div>
</template>
<script>
    export default {
    data() {
        return {
            user: {
                name: '猪小明',
                age: 28
            }
        }
    }
    }
</script>

image.png

动态插槽名

<template v-slot:[child]> ... </template>
这里的child会被作为表达式解析

vue3.2的写法

父组件:

      <HelloWorld msg="Hello Vue 3 + Vite">
        <template #default>
            默认插槽
        </template>
        <template #childsss>
            <div>我是具名插槽</div>
        </template>
        <template #child="{ child }">
            <div>我是作用域插槽{
   
   { child }}</div>
        </template>
    </HelloWorld>

子组件

<script setup>
import { ref } from 'vue'
defineProps({
    msg: String
})

const count = ref(0)
</script>

<template>
    <div>
        <slot>
            <h1>未传递内容插槽:{
   
   { msg }}</h1>
        </slot>
        <hr>
        <slot name="child" :child="count"></slot>
        <hr>
        <slot name="childsss"></slot>
    </div>
</template>

image.png

猜你喜欢

转载自blog.csdn.net/weixin_48164217/article/details/124274458