Vue-Router 4.0

本文介绍了如何在Vue3.0中使用vue-router4.x进行路由配置。首先,通过`npm init vitejs/app`创建Vue3应用,然后在`src/views`目录下创建Home和About组件。接着,使用`vue-router@next`安装最新版路由,并在`src/router/index.js`中设置路由,包括哈希模式、懒加载和404页面。在`main.js`中引入并挂载路由实例。此外,还展示了如何动态添加路由。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue-router有三个概念 route, routes, router。

vue3.0采用createRouter,不采用Vue.use(VueRouter)

npm init @vitejs/app vue3-vite --template vue

创建两个页面,用于路由切换,在 src 目录下新建 views 目录,添加 Home.vueAbout.vue 文件

注意 千万不要添加name  

<!--Home.vue-->
<template>
  Home
</template>

<script>
export default {
 
}
</script>
<!--About.vue-->
<template>
  About
</template>

<script>
export default {

}
</script>

然后通过 npm install vue-router@next 下载最新的路由插件。成功之后,在 src 目录下新建 router/index.js,添加如下代码:

import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
import Home from  '../components/Home.vue'
import NotFound from '../components/NotFound.vue'
const router = createRouter({
  history: createWebHashHistory(), // createWebHashHistory 为哈希模式的路由,如果需要选择 histiry 模式,可以用 createWebHistory 方法。
  routes: [ // routes 属性和 vue-router 3.0 的配置一样,通过数组对象的形式,配置路径对应展示的组件。
    {
      path: '/',
      component:Home,  
      children:[
          
    {
        //alias: '/home'  别名
        path: '/home',
        
    //重定向
        redirect:()=>import('../components/Home.vue'),  //路由懒加载 
      },
    {
      path: '/about',
      name: 'about',
      component: ()=>import('../components/About.vue'),
      meta:{
          username:'姓名'
      }
    },
    { //404
        path:'/:pathMatch(.*)*',
        name:'NotFound',
        component:NotFound
    }

      ]
    },
  

  ]
})

//动态添加路由
const home1={
    path:"/Home1",
    component:()=>import("../components/Home1.vue")
}
//通过router.addRoute()动态添加

router.addRoute(home1);

export default router

4.x动态路由

//main.js 把上述通过 export default router 抛出的路由实例引入 Vue 生成的实例

import { createApp } from 'vue'
import App from './App.vue'
import router from "./router/router.js";

createApp(App).use(router).mount('#app')

<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup

</script>

<template>
 
  <router-view></router-view>

</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值