【vue 3.0 中使用vue-router详细步骤】

Vue 3.0 中使用 vue-router 的步骤如下:

      • [1. 安装 vue-router:](#1. 安装 vue-router:)
      • [2. 创建一个单独的文件:](#2. 创建一个单独的文件:)
      • [3.main.js 配置路由:](#3.main.js 配置路由:)
      • [4. 在 App.vue 中使用 `<router-view>` 组件:](#4. 在 App.vue 中使用 <router-view> 组件:)
      • [5. 在路由的组件中使用 `<router-link>` 组件进行导航:](#5. 在路由的组件中使用 <router-link> 组件进行导航:)
      • 6.使用push进行跳转

1. 安装 vue-router:

bash 复制代码
npm install vue-router@4.0.0-beta.8

2. 创建一个单独的文件:

javascript 复制代码
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from './views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }
]

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

export default router

3.main.js 配置路由:

javascript 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')

4. 在 App.vue 中使用 <router-view> 组件:

js 复制代码
<template>
  <div>
    <h1>App.vue</h1>
    <router-view />
  </div>
</template>

5. 在路由的组件中使用 <router-link> 组件进行导航:

js 复制代码
<template>
  <div>
    <h2>About.vue</h2>
    <router-link to="/">Go to Home</router-link>
  </div>
</template>

6.使用push进行跳转

js 复制代码
<template>
  <div>
    <button @click="godetalis">跳转</button>
  </div>
</template>
  
  <script>
 import { useRouter } from "vue-router"; //引入路由

export default {
  setup() {
     const $route = useRouter();
    function godetalis() {
      $route.push({name: "你的路由名称"});
    }

    return {
      godetalis
    };
  }
};
</script>
  

以上就是在 Vue 3.0 中使用 vue-router 的详细步骤。

相关推荐
木斯佳5 小时前
前端八股文面经大全:腾讯前端暑期提前批一、二、三面面经(下)(2026-03-04)·面经深度解析
前端
bluceli5 小时前
前端国际化(i18n)实战指南:构建多语言应用的完整方案
前端
hh随便起个名5 小时前
React组件通信
前端·react.js·前端框架
前端 贾公子5 小时前
vite-plugin-eruda-pro 在vite中使用eruda
前端
Jackson__6 小时前
Agent Skill 和 Rules 有什么区别?
前端·agent·ai编程
不要卷鸿蒙啊6 小时前
【鸿蒙开发】HMRouter一款和好用的管理路由三方工具
前端·harmonyos
李剑一6 小时前
数字孪生大屏必看:Cesium 3D 模型选中交互,3 种高亮效果拿来就用!
前端·vue.js·cesium
奶昔不会射手6 小时前
自定义vue3函数式弹窗
前端·javascript·css
new code Boy6 小时前
前端全栈之路
前端
牛奶6 小时前
为什么敲几个字母就能访问网站?DNS原理大揭秘
前端·http·dns