动态组件&插槽

博客介绍了Vue的动态组件和插槽slot。动态组件可改变,通过Vue的component+is属性使用,还可搭配keep-alive组件缓存以提高效率。插槽slot用于预先保留内容,具名插槽在vue2.6以上被废弃,建议掌握新的v-slot指令,同时旧的也需了解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态组件

  1. 什么是动态组件?
    可以改变的组件
  2. 使用
    通过Vue提供一个component+is属性
  3. 动态组件指的就是component这个组件
  4. 案例-业务:点击一个按钮进行组件的切换
<div id="app">
    <button @click="change">切换</button>
    <keep-alive include="">
        <component :is="type"></component>
    </keep-alive>
</div>

<script>
Vue.component('Aa',{
    template:'<div>Aa</div>'
})
Vue.component('Bb',{
    template:'<div>Bb</div>'
})

new Vue({
    data:{
        type:Aa
    },
    method:{
        change(){
            this.type=(this.type==='Aa'?'Bb':'Aa')
        }
    }
}).$mount('#app')
</script>
  1. Vue提供了一个keep-alive的组件可以将我们的组件进行浏览器缓存,这样当我们切换组件时,就可以大大提高使用效率
  2. keep-alive也可以使用属性的形式呈现,但是如果我们搭配component的话,建议使用组件的形式。

插槽slot

  1. 作用/概念:预先将将来要使用的内容进行保留
  2. 具名插槽:给slot取个名字
  • 注意:以上两种形式在vue2.6以上被废弃
  • 为什么要用v-slot指令来代替呢?
  • 将具名插槽和作用域插槽进行统一
  • 要将这两个属性带有vue的标志,并且符合vue两个最大的特性之一:指令的概念
  • 建议:新的v-slot要掌握,旧的也掌握吧。
  1. 案例:
    <div id="app">
        <!--Hello组件-->
        <Hello>
            <div>
                这是填补内容
            </div>
        </Hello>
    </div>

    <!--template-->
    <template id="hello">
        <div>
            <slot></slot>
            <h3>this is Hello</h3>
        </div>
    </template>

    <script>
    Vue.componnet('Hello',{
        template:'#hello'
    })

    new Vue({
        el:'#app'
    })
    
    </script>
  1. 具名插槽
<div id="app">
    <Hello>
        <header slot="header">this is header</header>
        <footer slot="footer">this is footer</footer>
    </Hello>
</div>

<template id="hello">
<div>
    <slot name="header"></slot>
    <h3>this is content</h3>
    <slot name="footer"></slot>
</div>
</template>

<script>
    Vue.component('Hello',{
       template:'#hello' 
    })
    new Vue({

    }).$mount('#app')
</script>
  1. v-slot (vue 2.6)
  • 案例:
<div id="app">
    <Hello>
       <template v-slot="header">
            <h1>this is title</h1>
       </template>

       <p>A paragraph for the main content.</p>
       <p>And another one.</p>
       <template v-slot="footer">
            <h1>this is footer</h1>
       </template>
    </Hello>
</div>

<template id="hello">
    <div class="container">
        <header>
            <slot name="header"></slot>
        </header>
        <footer>
            <slot name="footer"></slot>
        </footer>
    </div>
</template>
<script>

  Vue.component('Hello',{
    template: '#hello'
  })

  new Vue({
    el: '#app',
  })
</script>

div>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值