插槽的作用

让用户可以拓展组件,去更好地复用组件和对其做定制化处理

Vue 实现了一套内容分发的 API,将<slot>元素作为承载分发内容的出口,这是vue文档上的说明。具体来说,slot就是可以让你在组件内添加内容的‘空间’。

  1. 父组件在引用子组件时希望向子组价传递模板内容<p>测试一下吧内容写在这里了能否显示</p>

  2. 子组件让父组件传过来的模板内容在所在的位置显示

  3. 子组件中的<slot>就是一个槽,可以接收父组件传过来的模板内容,<slot> 元素自身将被替换

  4. <myslot></myslot>组件没有包含一个 <slot> 元素,则该组件起始标签和结束标签之间的任何内容都会被抛弃

插槽的分类

vue 在 2.6 版本中,对插槽使用 v-slot 新语法,取代了旧语法的 slot 和 slot-scope,并且之后的 Vue 3.0 也会使用新语法,这并不是仅写法的不同,还包括了性能的提升

插槽分为普通插槽和作用域插槽,普通插槽为父组件传递数据/元素/组件给子组件,而子组件定义 <slot> 接收,当插槽有多个的时候,需要使用具名插槽 <slot name="xxx">,用于将数据绑定在指定的插槽

普通插槽

//  父组件
<template v-slot>
  <p>new Nian糕</p>
</template>
// 旧语法 只需一行:<p slot>old Nian糕</p> // 子组件
<slot />

具名插槽

// 父组件
<template v-slot:item>
  <p>new Nian糕</p>
</template>
// 旧语法:<p slot="item">old Nian糕</p> // 子组件
<slot name="item" />

作用域插槽为子组件 <slot> 绑定属性,传递数据给父组件,父组件通过 v-slot:xxx="props" 接收子组件传递的属性

作用域插槽 旧语法

//  父组件
<p slot="love" slot-scope="props">爱old {{ props.name }}真是太好了</p> // 子组件
<slot name="love" v-bind="{ name }" /> export default {
  data() {
    return {
      name: "Nian糕"
    }
  }
}

作用域插槽 新语法

//  父组件
<template v-slot:love="props">
  <p>爱new {{ props.name }}真是太好了</p>
</template> // 子组件
<slot name="love" v-bind="{ name }" /> export default {
  data() {
    return {
      name: "Nian糕"
    }
  }
}

案例2

//子组件 : (假设名为:ebutton)
<template>
    <div class= 'button'>
        <button> test</button>
        <slot name= 'one' :value1='child1'> 这就是默认值1</slot>    //绑定child1的数据
        <slot :value2='child2'> 这就是默认值2 </slot>  //绑定child2的数据,这里我没有命名slot
    </div>
</template> <script>
new Vue({
  el:'.button',
  data:{
    child1:'数据1',
    child2:'数据2'
  }
})
</script> //父组件:(引用子组件 ebutton)
<template>
    <div class= 'app'>
        <ebutton>
            <template v-slot:one = 'slotone'>
                {{ slotone.value1 }}    // 通过v-slot的语法 将子组件的value1值赋值给slotone
            </template>
            <template v-slot:default = 'slottwo'>
                {{ slottwo.value2 }}  // 同上,由于子组件没有给slot命名,默认值就为default
            </template>
        </ebutton>
    </div>
</template>

Vue3.0 slot简写

<!-- 父组件中使用 -->
 <template v-slot:content="scoped">
   <div v-for="item in scoped.data">{{item}}</div>
</template> <!-- 也可以简写成: -->
<template #content="{data}">
    <div v-for="item in data">{{item}}</div>
</template>

Vue3.0在JSX/TSX下如何使用插槽(slot)

先看看官方: https://github.com/vuejs/jsx-next/blob/dev/packages/babel-plugin-jsx/README-zh_CN.md#插槽

在 jsx 中,应该使用 v-slots 代替 v-slot

const A = (props, { slots }) => (
  <div>
    <h1>{ slots.default ? slots.default() : 'foo' }</h1>
    <h2>{ slots.bar?.() }</h2>
  </div>
); const App = {
  setup() {
    const slots = {
      bar: () => <span>B</span>,
    };
    return () => (
      <A v-slots={slots}>
        <div>A</div>
      </A>
    );
  },
}; // or const App = {
  setup() {
    const slots = {
      default: () => <div>A</div>,
      bar: () => <span>B</span>,
    };
    return () => <A v-slots={slots} />;
  },
}; // or
const App = {
  setup() {
    return () => (
      <>
        <A>
          {{
            default: () => <div>A</div>,
            bar: () => <span>B</span>,
          }}
        </A>
        <B>{() => "foo"}</B>
      </>
    );
  },
};

上面代码来源:Vue3.0在JSX/TSX下如何使用插槽(slot) https://www.cnblogs.com/pinkchampagne/p/14083724.html

关于jsx的,可以瞅瞅:vue3下jsx教学,保证业务上手无问题!https://juejin.cn/post/6911883529098002446

vue3 template与jsx写法对比

ue template中的slot插槽如何在JSX中实现?和template对比,更加清晰

template写法

子组件

<template>
    <div>
        <span>I'm Child</span>
        <slot></slot>
        <slot name="header"></slot>
    </div>
</template> <script>
export default {
    name: "Test"
}
</script>

父组件

<template>
    <TestComponent>
        <template #default>
            <span>这是默认插槽</span>
        </template>
        <template #header>
            <span>这是header插槽</span>
        </template>
    </TestComponent>
</template> <script>
import TestComponent from './TestComponent'
export default {
    name: "Parent",
    components: {
        TestComponent
    }
}
</script>

JSX的写法:

子组件

import { defineComponent } from "@vue/runtime-core";

export default defineComponent({
    name: "Test",
    render() {
        return (
            <>
                <span>I'm Child</span>
                { this.$slots.default?.() }
                { this.$slots.header?.() }
            </>
        )
    }
})
作用域插槽
import { defineComponent } from "@vue/runtime-core";

export default defineComponent({
    name: "Test",
    setup() {
        return {
            value: {
                name: 'xzw'
            }
        }
    },
    render() {
        return (
            <>
                <span>I'm Child</span>
                { this.$slots.content?.(this.value) }
            </>
        )
    }
})

父组件

import { defineComponent } from 'vue'
import TestComponent from './TestComponent' export default defineComponent({
    name: "Test",
    components: {
        TestComponent
    },
    render() {
        return (
            <TestComponent v-slots={{
                default: () => (
                    <div>这是默认插槽</div>
                ),
                header: () => (
                    <div>这是header插槽</div>
                )
            }}>
            </TestComponent>
        )
    }
})
作用域插槽
import { defineComponent } from 'vue'
import TestComponent from './TestComponent' export default defineComponent({
    name: "Test",
    components: {
        TestComponent
    },
    render() {
        return (
            <TestComponent v-slots={{
                content: scope => ( <div>{scope.name}</div>)
            }}>
            </TestComponent>
        )
    }
})

参考文章:

Vue3中的 JSX 以及 jsx插槽的使用 https://juejin.cn/post/6983130251702304781

Vue3 中插槽(slot)的用法 https://www.cnblogs.com/recode-hyh/p/14544808.html

vue3 学习 之 vue3使用 https://www.jianshu.com/p/91328e6934c9

【vue3】 使用JSX实现普通、具名和作用域插槽 https://blog.csdn.net/qq_24719349/article/details/116724681

转载本站文章《vue2升级vue3:Vue2/3插槽——vue3的jsx组件插槽slot怎么处理》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8683.html

vue2升级vue3:Vue2/3插槽——vue3的jsx组件插槽slot怎么处理的更多相关文章

  1. vue2升级vue3:vue2 vue-i18n 升级到vue3搭配VueI18n v9

    项目从vue2 升级vue3,VueI18n需要做适当的调整.主要是Vue I18n v8.x 到Vue I18n v9 or later 的变化,其中初始化: 具体可以参看:https://vue- ...

  2. vue2升级vue3指南(二)—— 语法warning&error篇

    本文总结了vue2升级vue3可能会遇到的语法警告和错误,如果想知道怎样升级,可以查看我的上一篇文章:vue2升级vue3指南(一)-- 环境准备和构建篇 Warning 1.deep /deep/和 ...

  3. vue2升级vue3:Vue Demij打通vue2与vue3壁垒,构建通用组件

    如果你的vue2代码之前是使用vue-class-component 类组件模式写的.选择可以使用 https://github.com/facing-dev/vue-facing-decorator ...

  4. vue2升级vue3:vue-i18n国际化异步按需加载

    vue2异步加载之前说过,vue3还是之前的方法,只是把 i18n.setLocaleMessage改为i18n.global.setLocaleMessage 但是本文还是详细说一遍: 为什么需要异 ...

  5. 手写 Vue 系列 之 从 Vue1 升级到 Vue2

    前言 上一篇文章 手写 Vue 系列 之 Vue1.x 带大家从零开始实现了 Vue1 的核心原理,包括如下功能: 数据响应式拦截 普通对象 数组 数据响应式更新 依赖收集 Dep Watcher 编 ...

  6. vue1升级到vue2的问题

    router 不能用map方法了,需要改router的结构改为 routers= [ { // 当没有匹配路由时默认返回的首页        path:'/index',        compone ...

  7. vue3 学习笔记 (四)——vue3 setup() 高级用法

    本篇文章干货较多,建议收藏! 从 vue2 升级到 vue3,vue3 是可以兼容 vue2 的,所以 vue3 可以采用 vue2 的选项式API.由于选项式API一个变量存在于多处,如果出现问题时 ...

  8. 学习 vue3 第一天 vue3简介,创建vue3项目 Composition Api 初识

    前言: 从今天开始来和大家一起学习 vue3 相信大家都不陌生,已经火了一段时间了,但是还是有不少人没有学习,那就跟着六扇老师来简单的入个门 废话不多说,来开始今天的学习 Vue3 简介: 2020年 ...

  9. Vue3实战系列:Vue3.0 + Vant3.0 搭建种子项目

    最近在用 Vue3 写一个开源的商城项目,开源后让大家也可以用现成的 Vue3 大型商城项目源码来练练手,目前处于开发阶段,过程中用到了 Vant3.0,于是就整理了这篇文章来讲一下如何使用 Vue3 ...

  10. Vue3.0聊天室|vue3+vant3仿微信聊天实例|vue3.x仿微信app界面

    一.项目简介 基于Vue3.0+Vant3.x+Vuex4.x+Vue-router4+V3Popup等技术开发实现的仿微信手机App聊天实例项目Vue3-Chatroom.实现了发送图文表情消息/g ...

随机推荐

  1. 题解 CF1401C

    题目大意: 给定一序列 \(A\),定义当且仅当 \(\gcd(a_i,a_j)=a_{min}\) 时,元素 \(a_i\) 和 \(a_j\) 可以交换. 问当前给定的序列 \(A\) 能否转化为 ...

  2. 字符串转换整数(atoi)(4.3leetcode每日打卡)

    一堆if不及python的一个正则表达式系列 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止.接下来的转化规 ...

  3. Python输入三个整数x,y,z,请把这三个数由小到大输出。

    break_out = False while 1: s = [] for i in range(3): x = int(input('请输入一个数:\n')) if x == -1: # 设计一个退 ...

  4. 解决Vscode中代码格式化时老换行

    问题: 小颖用vscode的格式化代码后发现代码老是换行,有时看起来就很难受,比如下面的: 问度娘后终于弄好啦,记录下,省的以后换电脑了重装了vscode又不会了,主要是百度给的解决方法好几个,但有的 ...

  5. Linux中execl函数详解与日常应用!

    Linux中execl函数详解与日常应用 execl是Linux系统中的一个系统调用,用于执行指定路径下的可执行文件.本文将详细介绍execl函数的使用方法和参数含义,并探讨其在日常开发中的常见应用场 ...

  6. 倒计时4天!解锁《2023 .NET Conf China》 云原生分会场精彩议程

    .NET Conf China 2023 定于 12 月16 日于北京举办为期一天的技术交流,届时会有.NET 领域专家与大家一同庆祝 .NET 8 的发布和回顾过去一年来 .NET 在中国的发展成果 ...

  7. [ABC261A] Intersection

    Problem Statement We have a number line. Takahashi painted some parts of this line, as follows: Firs ...

  8. [VBA] 实现SQLserver数据库的增删改查

    [VBA] 实现 SQLserver数据库的增删改查 问题背景 用于库存管理的简单Excel系统实现,能够让库管员录入每日出入库信息并进能够按日期查询导出数据,生成简要报表,以及数据修改与删除.非科班 ...

  9. Nginx服务器常用参数设置

    Nginx作为一个高性能的Web服务器和反向代理,它的性能可以通过调整底层操作系统的参数来进一步优化.以下是一些常见的操作系统级别的调整,通常针对Linux系统: File Descriptors L ...

  10. 华企盾DSC在苹果电脑上申请审批没有通知

    由于系统通知这里没有允许DSC通知,开启后即可.系统偏好设置-通知与专注模式-通知 ​