router-link 和router-view中插槽v-slot的使用

1,811 阅读1分钟

router-link

在使用 v-slot API 时,需要向 router-link 传入一个单独的子元素。否则 router-link 将会把子元素包裹在一个 span 元素内。

<router-link
  to="/about"
  custom
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <NavLink :active="isActive" :href="href" @click="navigate"
    >{{ route.fullPath }}</NavLink
  >
</router-link>
  • href:解析后的 URL。将会作为一个 a 元素的 href attribute。
  • route:解析后的规范化的地址。
  • navigate:触发导航的函数。会在必要时自动阻止事件,和 router-link 同理。
  • isActive:如果需要应用激活的 class 则为 true。允许应用一个任意的 class。
  • isExactActive:如果需要应用精确激活的 class 则为 true。允许应用一个任意的 class

router-view

router-view也提供给我们一个插槽,可以用于 和 组件来包裹你的路由组件: (keep-alive必须放在transition里)

  •  Component:要渲染的组件;
  •  route:解析出的标准化路由对象;
    <router-view v-slot="props">
        // 单个路由过度动效
      <transition :name="props.route.meta.transition">
        <keep-alive>
          <component :is="props.Component"></component>
        </keep-alive>
      </transition>
    </router-view>
熟练后可以直接按下面写,对对象进行解构
    <router-view v-slot="{ Component, route }">
  <!-- 使用任何自定义过渡和回退到 `fade` -->
  <transition :name="route.meta.transition || 'fade'">
    <component :is="Component" />
  </transition>
</router-view>