插槽的作用

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

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. MVC开发

    我们通过前面的章节可以看到:https://www.liaoxuefeng.com/wiki/1252599548343744/1266264917931808 Servlet适合编写Java代码,实 ...

  2. Excel数据统计与分析

  3. 【Javaweb】做一个房产信息管理系统一

    2019级<JAVA语言程序设计>     上机考试试题                                  2020.12.20     考试要求   一.本试卷为2019 ...

  4. 【Android】学习day05|RadioButton

    注意事项:当使用默认选中标签:check时,必须要给标签加id,否则失效. 这个没什么,挺简单的,就记录一下代码[监听事件] package com.example.app02; import and ...

  5. [USACO2007OPEN S] Catch That Cow S

    题目描述 FJ丢失了他的一头牛,他决定追回他的牛.已知FJ和牛在一条直线上,初始位置分别为x和y,假定牛在原地不动.FJ的行走方式很特别:他每一次可以前进一步.后退一步或者直接走到2*x的位置.计算他 ...

  6. 第一章 JavaEE应用和开发环境

    1.1 java EE应用概述 1.java EE的分层模型 数据库--[提供持久化服务]-->Domain Object层 --[封装]--〉DAO层--[提供数据访问服务]-->业务逻 ...

  7. 新冠肺炎病毒(Covid-19)检测系统

    一 .背景 新冠肺炎是一种新的呼吸道疾病,它由新型冠状病毒引起,而这种病毒以前从未在人类身上发现 过.新冠肺炎如何传播? 新冠肺炎很容易通过与新冠肺炎患者的密切接触(距离约 6 英尺或两臂长范围内)在 ...

  8. MybatisPlus最新代码生成器(version3.5.1+),自定义文件模板

    1.导入依赖(我这里用的是gradle构建工具,maven也一样啦~) plugins { id 'java' id 'org.springframework.boot' version '2.7.3 ...

  9. JXNU acm选拔赛 不安全字符串

    不安全字符串 Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other) Total Submis ...

  10. 初次认识 Git (v2.x)

    什么是版本控制? 版本控制,也称为源代码控制,是一种跟踪和管理软件代码变更的实践.版本控制系统是软件工具,可帮助软件团队管理源代码随时间推移而发生的变更.随着开发环境的加速,版本控制系统可以帮助软件团 ...