浅析<router-view> v-slot 事例和应用

官方关于<router-link> 的 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>

  但对于初学者在刚开始了解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的解释:

  • Component: 要传递给<component> 的 VNodes 是 prop。
  • route: 解析出的标准化路由地址。

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

<component :is="currentTabComponent"></component>

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

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

  而上面的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>

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

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

  应用:比如我们做官网时,要做 PC 端和 Mobile 端,我们可以独立写文件,但是使用同一套路由,然后动态去加载 PC 或 Mobile 下的 Component

<template>
    <router-view v-slot="{ Component }">
        <component :is="Component" />
    </router-view>
</template>

 

posted @ 2018-03-06 21:25  古兰精  阅读(2777)  评论(0编辑  收藏  举报