路由
路由是一种映射关系
vue中的路由是路径和组件的映射关系
为何使用路由
单页面应用(spa):所有功能在一个html页面上实现
vue路由-vue-router使用
1.下载vue-router@3.6.2包
2.在main.js里面导入vue-router包 import VueRouter from 'vue-router'
3.在main.js里面 使用Vue.use(VueRouter)将 VueRouter 注册为Vue插件
4.配置 路由规则数组 组件和路径的映射关系 const routes=[ {
path:'/login',
compoent:Login
}]
5.创建路由对象const router= new VueRouter({
路由规则数组 routes})
6.将路由对象注入到 new Vue{{路由对象}}
new Vue({
router,
render: h => h(App)
}).$mount('#app')
7.在main.js里面 引入对应的组件
import Reg from './components/Login'
8.会到App.vue中适应 <router-view></router-view>占位符
自动下载包,自动生成
步骤
1 4 5 6
项目创建好后
1.在 router的index.js中 import引入Login.vue文件
2.写路由规则 路径和组件的映射关系
const routers=[
{
path:'/login',
component:Login
}
]
3.在main.js中引入router包 并 将路由对象注入到 new Vue{{路由对象}}
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
4.在App.vue中引入 Login.vue 用<router-view><.router-view>占位符
2.声明式导航
语法
<router-link></router-link>
这是一个 组件 但是这个组件最终会被解析a标签 头属性 会被解析成href to属性的值 不需要加#
<a href="#/find">发现音乐</a>
//等价于
<router-link to="/find">发现音乐</router-link>
2.声明式导航 传参
在router-link上的to属性传值, 语法格式如下
/path?参数名=值
/path/值 – 需要路由对象提前配置 path: “/path/参数名”
对应页面组件接收传递过来的值
$route.query.参数名
$route.params.参数名
?传参
在App.vue中写
<router-link to="/my?name=111"> 我的音乐</router-link>
在对应的vue文件中通过
<p>人名{{$route.query.name}}</p>获取参数
/传参
1.在App.vue中写入
<router-link to="/part/222">朋友</router-link>
2.在路由规则中对应的 /part组件/:参数名
3.在对应的path.vue界面
<p>{{$route.params.uname}}</p>//获取uname的参数值
路由重定向
网页打开url默认hash值是/路径
redirect是设置要重定向到哪个路由路径
例如: 网页默认打开, 匹配路由"/", 强制切换到"/find"上
//在路由规则前
const routes = [
{
path: '/',
// 第一次打开浏览器时 浏览器的路径是/
redirect:'/find' //重定向默认打开跳转到指定的页面中
},//一般放在数组最前面
}
]
vue路由-404页面
默认给一个404页面
语法: 路由最后, path匹配*(任意路径) – 前面不匹配就命中最后这个, 显示对应组件页面
-
创建NotFound页面
-
引入 NotFound页面
<template>
<img src="../assets/404.png" alt="">
</template>
<script>
export default {
}
</script>
<style scoped>
img{
width: 100%;
}
</style>
在路由规则 最后面 加入
{
path: '*',
component: NotFound // 注意 要放在最后 代码从上往下执行 未找到的404页面设置
},
二级路由
{
path: '/find',
component: Find,
children:[
{
// 二级路由path中不加 / **
path: 'recommend',
component:Recommend
},
{
// 二级路由path中不加 / **
path: 'ranking',
component:Ranking
},
{
// 二级路由path中不加 / **
path: 'songlist',
component:SongList
}
]
},
在find文件中
<div class="nav_main">
<router-link to="/find/recommend">推荐</router-link>
<router-link to="/find/ranking">排行榜</router-link>
<router-link to="/find/songlist">歌单</router-link>
</div>
路由守卫
// 目标: 路由守卫
// 场景: 当你要对路由权限判断时
// 语法: router.beforeEach((to, from, next)=>{//路由跳转"之前"先执行这里, 决定是否跳转})
// 参数1: 要跳转到的路由 (路由对象信息) 目标
// 参数2: 从哪里跳转的路由 (路由对象信息) 来源
// 参数3: 函数体 - next()才会让路由正常的跳转切换, next(false)在原地停留, next("强制修改到另一个路由路径上")
// 注意: 如果不调用next, 页面留在原地
// 例子: 判断用户是否登录, 是否决定去"我的音乐"/my
const isLogin = true; // 登录状态(未登录)
//beforeEach() 路由跳转之前经过这
router.beforeEach((to, from, next) => {
if (to.path === "/my" && isLogin === false) {
alert("请登录")
next(false) // 阻止路由跳转
} else {
next() // 正常放行
}
})