vue-router有三个概念 route, routes, router。
vue3.0采用createRouter,不采用Vue.use(VueRouter)
npm init @vitejs/app vue3-vite --template vue
创建两个页面,用于路由切换,在 src 目录下新建 views 目录,添加 Home.vue 和 About.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>
本文介绍了如何在Vue3.0中使用vue-router4.x进行路由配置。首先,通过`npm init vitejs/app`创建Vue3应用,然后在`src/views`目录下创建Home和About组件。接着,使用`vue-router@next`安装最新版路由,并在`src/router/index.js`中设置路由,包括哈希模式、懒加载和404页面。在`main.js`中引入并挂载路由实例。此外,还展示了如何动态添加路由。
8014

被折叠的 条评论
为什么被折叠?



