• 浅析<router-view> v-slot事例


    官方关于 的 v-slot的相关介绍:
    https://router.vuejs.org/zh/api/#router-view-%E7%9A%84-v-slot
    并给出了一个例子:

    <router-view v-slot="{ Component, route }">
      <transition :name="route.meta.transition || 'fade'" mode="out-in">
        <keep-alive>
          <suspense>
            <template #default>
              <component
                :is="Component"
                :key="route.meta.usePathKey ? route.path : undefined"
              />
            template>
            <template #fallback> Loading... template>
          suspense>
        keep-alive>
      transition>
    router-view>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    但对于初学者在刚开始了解vue或者刚开始入手和摸索学习的时候看到上面的例子应该多少有些懵,上面的{ Component, route }是什么东西,是怎么来的是自己定义的吗?

    但你看到前面的v-slot,实际上他就是对应vue的插槽
    参考官方文档:https://v3.cn.vuejs.org/guide/component-slots.html,你不难发现它就是作用域插槽下的 解构插槽 Prop,官方给出的例子也类似于v-slot="{ Component, route }"的写法。实际上就是让router-view的插槽能够访问子组件中的数据,访问的数据就是Component和route 。

    官方给出Component和route的解释:

    我们再去参考vue组件基础中的动态组件,你不难发现,其实有相关的介绍:

    <component :is="currentTabComponent">component>
    
    • 1

    在上述示例中,currentTabComponent 可以包括:

    • 已注册组件的名字,或
    • 一个组件选项对象
    <component
      :is="Component"
      :key="route.meta.usePathKey ? route.path : undefined"
    />
    
    • 1
    • 2
    • 3
    • 4

    而上面的router-view插槽中的Component就是一个组件选项对象,如果你在浏览器的控制台查看,它类似于下面的结构:
    在这里插入图片描述
    而route就是RouteLocationNormalized,你可以获取RouteLocationNormalized中的参数,比如meta中你自定义的内容。假如,你在meta定义了一个参数cacheable,用来区分是否需要缓存组件,你就可以做如下操作:

    <router-view v-slot="{ Component, route }">
      <keep-alive v-if="Component">
        <component :is="Component" v-if="route.meta.cacheable">component>
      keep-alive>
      <component :is="Component" v-if="!route.meta.cacheable">component>
    router-view>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    而关于keep-alive,大家可以参考,在动态组件上使用-keep-alive。当在某些组件之间切换的时候,你有时会想保持这些组件的状态,以避免反复渲染导致的性能问题,我们更希望那些已经打开的组件实例能够被在它们第一次被创建的时候缓存下来。为了解决这个问题,我们可以用一个 元素将其动态组件包裹起来。

    suspense看官方介绍是一个新增的功能,具体参考:https://v3.cn.vuejs.org/guide/migration/suspense.html
    是一个试验性的新特性,用来在正确渲染组件之前进行一些异步操作。目前不推荐在生产使用。

    总结:
    就单纯看 v-slot这个事例就简单几行代码,但它需要我们把vue的基础和深入组件掌握好,要不看起来就比较懵,不知道什么意思。

  • 相关阅读:
    CloudCompare&PCL ICP配准(点到面)
    AtCoder Beginner Contest 332
    1355:字符串匹配问题(strs)
    图神经网络驱动的交通预测技术:探索与挑战
    虚拟机(VM)监控工具
    【目录】RV1103/RV1106开发记录
    Linux 常用命令
    【CVPR 2022】HDR-NeRF: High Dynamic Range Neural Radiance Fields
    【MySQL】JDBC编程
    内存泄漏?
  • 原文地址:https://blog.csdn.net/m13012606980/article/details/126028170