Bootstrap

vue3+router 命名路由-编程式导航

命名路由

除了 path 之外,你还可以为任何路由提供 name

编程式导航

1.字符串模式
2.对象模式
3.命名式路由模式

// router/index.ts
//引入路由对象
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

//路由数组的类型 RouteRecordRaw
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: 'Login', //router-link跳转方式需要改变 变为对象并且有对应name
    component: () => import("../components/login.vue"),
  },
  {
    path: "/home",
    name: 'Home',
    component: () => import("../components/home.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

<template>
  <div>
    <div>
      <!-- router-link跳转方式需要改变 变为对象并且有对应name -->
      <!-- <router-link :to="{ name:'Login' }">Login</router-link>
    <router-link :to="{ name: 'Home' }">Home</router-link> -->
      <!-- 编程式导航 -->
      <!-- <button @click="toPath('/')">Login</button>
      <button @click="toPath('/home')">Home</button> -->

        <button @click="toPath('Login')">Login</button>
      <button @click="toPath('Home')">Home</button>

    </div>
    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";

const router = useRouter();
// 编程式导航
const toPath = (url: string) => {
  // router.push(url)
  // router.push({
  //   path: url
  // });
  
  router.push({
    name: url
  });
};
</script>

<style scoped></style>


;