【Vue-Router】路由跳转

1. 路由标签

App.vue

<template>
  <h1>hello worldh1>
  <div>
    <router-link to="/">Loginrouter-link>
    <router-link style="margin: 10px;" to="/reg">Regrouter-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 worldh1>
  <div>
    <router-link :to="{name:'Login'}">Loginrouter-link>
    <router-link style="margin: 10px;" :to="{name:'Reg'}">Regrouter-link>
  div>
  <hr>
  <router-view>router-view>
template>

<script setup lang="ts">

script>

<style scoped>

style>

3. 标签

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

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 worldh1>
  <div>
    <button @click="toPage('./')">Loginbutton>
    <button @click="toPage('./reg')">Regbutton>
  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 worldh1>
  <div>
    <button @click="toPage('Login')">Loginbutton>
    <button @click="toPage('Reg')">Regbutton>
  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>

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