Vue路由最全详解 创建路由

vue安装路由

安装:npm i vue-router@next -S 安装vue3下的路由

步骤:

1.创建一个路由文件 router.js

2.导入路由模块

import {createRouter,createWebHashHistory} from 'vue-router'

 3.引入要链接的组件

import test01 from './components/test01.vue'

 4.创建路由路径

const routes = [
  {
    path: '/', //跳转的路径
    name: 'test01', //路径的名字
    component:test01, //组件名字
  },
  {path: '/test02', name: 'test02', component:test02,},
  {path: '/test03', name: 'test03', component:test03, }
]

 5.创建路由对象

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})

 6.把对象导出给外部使用 

export default router 

 

路由的定义模式

1.hash模式:路径里会带#,会显示锚点,支持所有浏览器,只能改变#后面的路由名称进行跳转。

2.history模式:路径和正常网络路径一样,会存储路径的历史记录,每次刷新页面,就会重新请求后台服务器,会执行多次,会耗时间。

3.abstract模式:适用于所有的js环境,可以在node环境里使用,可以在node环境下执行代码跳转。

createWebHashHistory -> hash模式

createWebHistory -> history模式

引用路由

<router-link to="/">菜单1</router-link> 定义菜单
<router-view></router-view> 显示路由里的内容

属性:

        to:跳转路径

        replace 跳转路径,导航后不会留下history历史记录

        tag 替换 router-link 显示的标签

        active-class 设置菜单被选中的样式

const routes = [
    // {path:'/', redirect:"test02"}, //默认路径
    {
        path: '/test01', //跳转的路径
        name: 'test01', //路径的名字
        component:test01, //组件名字
    },
    {path: '/test02', name: 'test02', component:test02, },
    {path: '/test03', name: 'test03', component:test03, },
    {path: '/test04', name: 'test04', component:test04, },
    {path: '/test05', name: 'test05', component:test05, },
    {path: '/test06', name: 'test06', component:test06, }
]

js下跳转路由

        通过path跳转 

this.$router.push({path:"/test01", query:{name:"ton"}})
this.$router.push({path:"/test01", params:{name:"ton"}})

        通过name跳转 

this.$router.push({name:"test-01", params:{name:"ton"}})

query和params传参的区别:

query会显示传参内容,params不会显示参数

[this.$route.query.name](http://this.$route.query.name)
[this.$route.params.name](http://this.$route.params.name)

路径重定向:Redirect

当用户想访问A页面,但是强制用户跳转到B页面,用重定向。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值