vue插槽

插槽

插槽顾名思义,是一个容器,用来放置一些内容,也叫内容分发器。这些内容可以是文本、组件、html代码。插槽通常用来动态的插入一些内容。

定义插槽

插槽的关键词是slot,在要插入内容的地方放置,一个插槽就定义好了,可以防止你想放置的内容

  1. 基本插槽
 <div id="app">
        <slot>hello worldslot>
 div>

在插槽中间写入hello world

const app = new Vue({
        el: "#app",
        data: {

        },
        methods: {

        }
    })

在这里插入图片描述
结果正如我们所预想的一样,显示出来我们输入的文本。我们除了可以直接将内容放在slot标签之间外,还可以将内容放在组件中

<div id="app">
        <cone>
            hello in component
        cone>
    div>

将内容直接放在组件中

 Vue.component("cone", {
        template: `

` }) const app = new Vue({ el: "#app", data: { }, methods: { } })

在组件中放置插槽,当解析的时候文本会放在slot中
vue插槽_第1张图片
如果想要插入多行,可以复制文本或在组件中多写几个slot,

<div id="app">
        <cone>
            hello in component
        cone>
    div>
 Vue.component("cone", {
        template: `

` }) const app = new Vue({ el: "#app", data: { }, methods: { } })

vue插槽_第2张图片
那么要在不同的插槽里插入不同的内容怎么办呢,需要使用具名插槽。
2. 具名插槽
故名思意,具名插槽就是有名字的插槽,可以通过名字进行识别,进行精准投放内容。

Vue.component("cone", {
        template: `

`
}) const app = new Vue({ el: "#app", data: { }, methods: { } })

在组件中定义插槽的时候需要加上那么属性

<div id="app">
        <cone>
            <template v-slot:p1>
              content in p1
          template>
            <template v-slot:p2>
            content in p2
        template>
            <template v-slot:p3>
            content in p3
        template>
        cone>
    div>

在使用的时候需要使用template标签,在该标签中使用v-slot指令将插槽的name只传入,在template中写入内容。
vue插槽_第3张图片
3. 作用域插槽
作用于插槽可以访问子组件的作用域。
在定义时需要在slot标签上绑定一个属性,属性值,是从子组件传递的值。

 Vue.component("cone", {
        data() {
            return {
                hello: "hello world"
            }

        },
        template: `

`
}) const app = new Vue({ el: "#app", data: { }, methods: { } })
<div id="app">
        <cone>
            <template v-slot:p1="slotPros">
            {{slotPros.text}}
          template>
            <template v-slot:p2>
            content in p2
        template>
            <template v-slot:p3>
            content in p3
        template>
        cone>
    div>

在父级组件中通过template的v-slot指令获取子组件传过来的值
vue插槽_第4张图片

你可能感兴趣的:(Vue,vue)