【Vue-Router】重定向

【Vue-Router】重定向_第1张图片
First.vue

<template>
  <h1>First Secitonh1>
template>

Second.vueThird.vue代码同理

UserSettings.vue

<template>
  <h1>UserSettingsh1>
  <router-link to="/settings/children1">children1router-link>
  <br />
  <router-link to="/settings/children2">children2router-link>
  <br>
  <button @click="toBackPage">返回button>
  <hr>
  <router-view>router-view>
  <router-view name="a">router-view>
  <router-view name="b">router-view>
template> 

<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const toBackPage = () => {
  router.go(-1);
}
script>

<style scoped>style>

index.ts

import { createRouter, createWebHistory } from 'vue-router'
import First from '../components/First.vue'
import Second from '../components/Second.vue'
import Third from '../components/Third.vue'
import UserSettings from '../components/UserSettings.vue'

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/settings',
      component: UserSettings,
      // 当访问 /settings 时,会直接重定向访问 /settings/children1

      // 写法一:字符串形式
      // redirect:'/settings/children1',
      // 写法二:对象形式
      // redirect: {
      //   path: '/settings/children1'
      // }
      // 写法三:回调函数形式
      redirect: to => {
        console.log(to);
        // 可以 return 对象(此时可以传参) 或者 字符串
        // return '/settings/children1'
        return {
          path: '/settings/children1',
          query: {
            name: 'uzi'
          }
        }
      },
      children: [
        {
          path: 'children1',
          components: {
            default: First,
            a: Second,
            b: Third,
          },
        },
        {
          path: 'children2',
          components: {
            default: Third,
            a: Second,
            b: First,
          },
        },
      ]
    },

  ],
})

App.vue

<template>
  <h1>Nested Named Viewsh1>
  <hr>
  <router-view>router-view>
  <hr>
template>

<script setup lang="ts">

script>

<style scoped>style>

【Vue-Router】重定向_第2张图片
【Vue-Router】重定向_第3张图片

你可能感兴趣的:(Vue-Router,vue.js,javascript,前端)