Vue 25 | vue-router使用

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来进行挂载
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值