插槽的作用

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

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. python环境配置常用命令

    #安装前请更新 sudo apt-get update python -m pip install --upgrade pip #升级PIP版本 sudo apt-get install python ...

  2. String 的 indexOf 与 search 方便的区别

    String 这个对象里面包含许多方法 今天只要讲 indexOf 与 search 1.indexOf stringObject.indexOf(searchvalue,fromindex) 2.s ...

  3. go基础-函数

    概述 在任何语言中函数都是极其重要的内容,业务功能都是由一个或多个函数组合完成.go语言是函数式编程语言,函数是一等公民,可以被传递.有函数类型,go语言有三种类型的函数,普通函数.匿名函数(Lamb ...

  4. JAVAweek8

    编程,要学会将大问题逐渐分解成一个个小问题,逐步完成. 将整个程序分成若干个组件(分解) 将多次出现的相似功能设成独立的方法(模式识别.抽象.算法) 调试每个独立组件的健壮性(单元测试) 按照功能要求 ...

  5. 23C新特性:True Cache的介绍

    我们的文章会在微信公众号"Oracle恢复实录"和博客网站"https://www.cnblogs.com/www-htz-pw/" 同步更新 ,欢迎关注收藏, ...

  6. Why Microservices ?

    微服务(Microservices)是一种软件架构设计风格,其中应用程序由一组小型.独立.自治的服务组成,这些服务共同工作以构建整体应用.每个服务都专注于一个特定的业务功能,可以独立部署.扩展和维护. ...

  7. 【译】使用 GitHub Copilot 编写 Git 提交

    在花费数小时修复 bug 或更新特性之后,我们开发人员最不愿意做的事情往往是仔细说明 Git 提交的内容.最新的 Visual Studio 预览版可以帮到您.使用新的生成 Git 提交消息特性来帮助 ...

  8. jvm的jshell,学生的工具

    jshell  在我眼里,只能作为学校教学的一个玩具,事实上官方也做了解释,以下是官方的解释: 在学习编程语言时,即时反馈很重要,并且 它的 API.学校引用远离Java的首要原因 教学语言是其他语言 ...

  9. 文心一言 VS 讯飞星火 VS chatgpt (154)-- 算法导论12.3 1题

    一.用go语言,给出 TREE-INSERT 过程的一个递归版本. 文心一言,代码不能运行: 下面是用 Go 语言实现一个递归版本的 TREE-INSERT 过程的代码: package main i ...

  10. [USACO2007NOVS] Milking Time S

    题目描述 Bessie 可以在接下来 \(N\) 个小时内产奶,为了方便,我们把这 \(N\) 个小时 \(0\dots N-1\) 编号. FJ 在这 \(N\) 个小时内有 \(M\) 段时间可以 ...