vue-router快速使用

介绍

Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。

 目前Vue路由最新的版本是4.x版本。

vue-router是基于路由和组件的路由用于设定访问路径, 将路径和组件映射起来.在vue-router的单页面应用中, 页面的路径的改变就是组件的切换.

快速使用

 安装 npm i vue-router     

新建文件 

import {createRouter, createWebHistory} from 'vue-router'
//import oneView from '@/views/oneView'
const routers = [
   {
    path:'/one',
    //component:oneView,
     component:()=>import('@/views/oneView.vue'),
  
},
]

const router = createRouter({
// createWebHashHistory hash模式
// history 模式
    history: createWebHistory(), 
    routes:routers
})
export default router

其中组件有两种导入方法 路由模式可设置成hash或history模式

main.js中

app.vue中

 

重定向与别名

重定向也是通过 routes 配置来完成,下面例子是从 /重定向到 /one

const routes = [{ path: '/', redirect: '/one' }]

重定向是指当用户访问 /时,URL 会被 / 替换,然后匹配成 /。那么什么是别名呢?

将 / 别名为 /home,意味着当用户访问 /home 时,URL 仍然是 /home,但会被匹配为用户正在访问 /

const routes = [{ path:/one', component: oneView, alias: '/oneView' }]

  404 Not found 路由

router.js中

const NotFound= {

    template: '<div>404</div>',

  }

在routes中加入

{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },

带参数的路由

const User = {

    template: '<div>User {{ $route.params.id }}</div>',

  }

{ path: '/users/:id', component: User },

 嵌套路由

 router.js中添加

const childOne = {
    template: '<div>childOne</div>'
}
const childTwo = {
    template: '<div>childTwo</div>'
}
const routers = [
  
    {
        path: '/one',
        component: oneView,
        children: [{
            path: 'childOne',
            component: childOne
        }, {
            path: 'childTwo',
            component: childTwo
        }
        ]

    },

]

oneView.vue中

<div>
  <div> oneView</div>
  <router-link to="/one/childOne">childOne</router-link>
  <router-link to="/one/childTwo">childTwo</router-link>
  <router-view></router-view>
</div>

添加路由

在router.js中添加

const twoView = {
    template: '<div>twoView</div>'
}
const routers2 = [{
    path:'/two',
    component:twoView
}]
router.addRoute(routers2[0])

这时two被添加到跟路由上

添加至其他节点

const routers = [
    {
        path: '/one',
        component: oneView,
        name:'one',
        children: [{
            path: 'childOne',
            component: childOne
        }, {
            path: 'childTwo',
            component: childTwo
        }
        ]

    }

]
const routers2 = [{
    path:'two',
    component:twoView
}]
router.addRoute('one',routers2[0])

命名视图
const top = {
    template: '<div>top</div>'
}
const footer = {
    template: '<div>footer</div>'
}
//注意 component+s
const routers = [
    {
    path:'/main',
    components:{top:top,footer}
}]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值