vue-router使用流程
1、下载vue-router依赖
2、编写路由配置,全局注入router
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter)// 全局注入VueRouter
// 因为整个项目中都会需要使用到router的相关属性方法
export default new VueRouter({
routes:[
{
path:'/',// 定义根
redirect:'/home',// 重定义根,因为具体的内容在嵌套的路由中
// 需要重定义根进入到嵌套路由children中
component:()=>import('../page/main'),// main页面
children:[
{
path:'/home',
component:()=>import('../page/home')
},
{
path:'/list',
component:()=>import('../page/list')
},
{
path:'/form',
component:()=>import('../page/form')
}
]
}
]
})
3、在vue实例上进行挂载
4、使用router-view用于承载页面
router 3.x与4.x的区别
官方文档 https://router.vuejs.org/zh/guide/migration/index.html
创建router实例
- 3.x使用new VueRouter创建,4.x使用createRouter创建
// 3.x
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
})
// 4.x
const router = VueRouter.createRouter({// 解构出createRouter这个方法
// 通过调用这个方法来创建router实例
routes, // `routes: routes` 的缩写
})
- 3.x的路由模式传入的是mode值为’hash’和’history’,一般网址上带有井号的就是hash模式
- 4.x传入的是history值为createWebHashHistory()和createWebHistory()
// 3.x
const router = new VueRouter({
mode: 'history', // mode: 'hash'
routes: [...]
})
// 4.x
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(), // 这是hash模式
// history: createWebHistory()// 这是history模式
routes,
})
- 3.x的挂载方式是通过router属性来挂载,4.x通过链式操作的方式进行挂载
// 3.x
new Vue({
router,
render: h => h(App),
}).$mount('#app')
// 4.x
createApp(App).use(router).mount('#app')
//用createApp方法创建vue实例,使用use方法把router实例传入,调用.mount来进行挂载