0
点赞
收藏
分享

微信扫一扫

【Vue-Router】路由跳转

三维控件研究 2023-08-14 阅读 122

1. 路由标签

App.vue

<template>
  <h1>hello world</h1>
  <div>
    <router-link to="/">Login</router-link>
    <router-link style="margin: 10px;" to="/reg">Reg</router-link>
  </div>
  <hr>
  <router-view></router-view>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

2. 命名路由

index.ts

import { createRouter, createWebHistory, RouteRecordRaw, createWebHashHistory } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: 'Login',
    component: () => import("../components/login.vue")
  },
  {
    path: "/reg",
    name: 'Reg',
    component: () => import("../components/reg.vue")
  }
]

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

export default router

App.vue

<template>
  <h1>hello world</h1>
  <div>
    <router-link :to="{name:'Login'}">Login</router-link>
    <router-link style="margin: 10px;" :to="{name:'Reg'}">Reg</router-link>
  </div>
  <hr>
  <router-view></router-view>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

3. <a>标签

<a>标签替换存在默认行为,会刷新页面

index.ts

<template>
  <h1>hello world</h1>
  <div>

    <a href="/">Login</a>
    <a href="/reg">Reg</a>
  </div>
  <hr>
  <router-view></router-view>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

4. 编程式导航

App.vue

<template>
  <h1>hello world</h1>
  <div>
    <button @click="toPage('./')">Login</button>
    <button @click="toPage('./reg')">Reg</button>
  </div>
  <hr>
  <router-view></router-view>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const toPage = (path: string) => {
  // 1.字符串
  // router.push(path);
  // 2.对象
  router.push({
    path: path
  })
  // 3.命名式
}
</script>

<style scoped></style>
<template>
  <h1>hello world</h1>
  <div>
    <button @click="toPage('Login')">Login</button>
    <button @click="toPage('Reg')">Reg</button>
  </div>
  <hr>
  <router-view></router-view>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const toPage = (path: string) => {
  // 1.字符串
  // router.push(path);
  // 2.对象
  // router.push({
  //   path: path
  // })
  // 3.命名式
  router.push({
    path: path
  })
}
</script>

<style scoped></style>
举报

相关推荐

0 条评论