Vue组件(三)-内置组件component、transition、 transition-group、keep-alive、slot

component组件

动态绑定组件,根据数据不同更换不同的组件,component通过属性is的值可以渲染不同的组件。

下面的例子是一个简单的切换编辑器的组件,只在演示component组件的用法

<div class="editors">
   <button @click="currentEditor='TinymceEditor'">富文本编辑器</button>
   <button @click="currentEditor='MarkdownEditor'">Markdown编辑器</button>
   <component :is="currentEditor"></component>
 </div>

Vue部分

components: {
  MarkdownEditor, TinymceEditor
},
data () {
  return {
    currentEditor: 'TinymceEditor',
  }
}

如果监听两个编辑器组件的生命周期会发现,每次切换,组件都会重走生命周期

keep-alive组件

能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。<keep-alive>包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
keep-alive组件的属性:

  • include: 字符串或正则表达式。只有匹配的组件会被缓存。
  • exclude: 字符串或正则表达式。任何匹配的组件都不会被缓存。
    PS:这里说的匹配的组件是通过vue组件name属性匹配的,而不是router配置的name
<!-- 失活的组件将会被缓存!-->
<div class="editors">
   <button @click="currentEditor='TinymceEditor'">富文本编辑器</button>
   <button @click="currentEditor='MarkdownEditor'">Markdown编辑器</button>
   <keep-alive include="TinymceEditor">
   	  <component :is="currentEditor"></component>
   </keep-alive>
 </div>

这时候,如果监听两个编辑器组件的生命周期会发现,每次切换,TinymceEditor组件created之后不会被销毁,MarkdownEditor组件则会重走生命周期。

transition组件

transition组件在下列情况下为组件(或元素)的载入和切换提供过渡或动画效果

  • 条件渲染 (使用 v-if)
  • 条件展示 (使用 v-show)
  • 动态组件
  • 组件根节点

过渡的状态分为进入/离开两大类,如下面的例子中,为组件进入绑定了过渡效果

<transition
  enter-active-class="animate__animated animate__fadeInRight"
  :duration="{ enter: 1000 }"
>
  <component :is="currentEditor"/>
</transition>

transition组件的使用方式比较多,这里只介绍一种与animate.css的方法,详细可以参考官网
https://cn.vuejs.org/v2/guide/transitions.html

transition-group组件

transition-group组件为多个元素/组件的过渡效果

slot组件

slot又称插槽,在子组件中使用slot组件,在组件渲染时,slot组件将会被替换为父组件的模板内容,slot组件相当于子组件留给父组件的占位符

父组件

<child>
  <p slot="title">具名插槽title的内容</p>
  <p>默认插槽的内容</p>
</child>

子组件(Child)

  <div>
    <slot name="title"></slot>
    <slot></slot>
  </div>

默认插槽和具名插槽

<slot> 组件拥有name属性,可以用来定义额外的插槽,如果不指定则默认为“default”,这样的插槽称为默认插槽匿名插槽,指定name属性则称为具名插槽

作用域插槽

通过作用域插槽,父组件可以获取到子组件的数据。

  • 子组件在<slot>标签上绑定属性值
  • 父组件使用<template>标签的 slot-scope属性接收数据

子组件(Child)

<div>
  <slot name="content" :msg="{title:'我是子组件的数据'}"></slot>
</div>

父组件

<child>
  <template slot="content" slot-scope="slotProps">
    {{slotProps.msg.title}}
  </template>
</child>

slotProps可以随意命名,也可以使用解构的方式{msg}替换slotProps

Vue2.6,增加了一个新指令v-slot,用于统一具名插槽和作用域插槽

父组件:

<child>
  <template v-slot:title>具名插槽</template>
  <template v-slot:content="{msg}">解构插槽:{{msg.title}}</template>
</child>

子组件:

<div>
  <slot name="title"></slot>
  <slot name="content" :msg="{title:'我是子组件的数据'}"></slot>
</div>
  • v-slot指令可以绑定动态参数
<child>
  <template v-slot:[dynamicSlotName]>具名插槽</template>
</child>
  • v-slot指令可以简写,将v-slot:替换为字符 #
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值