- 用于将任意信息附加到路由规则上。eg:过渡名称、路由访问权限…
- 可通过配置
meta
属性来设置路由元信息。可以在导航守卫上访问 meta
属性值。
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
Vue.use(VueRouter);
const routes = [
path: '/home',
name: 'Home',
component: Home,
meta: { name: 'myHome' },
children: [
path: 'son',
name: 'Son',
component: () => import('../views/Son.vue'),
props(route) {
return {
id: route.query.id,
name: route.query.name,
way: route.query.way,
meta: { name: 'mySon' },
path: '/about',
name: 'About',
component: () => import('../views/About.vue'),
meta: { name: 'myAbout' },
const router = new VueRouter({ routes });
router.afterEach((to, from) => {
document.title = to.meta.name;
});
export default router;
hash
模式:
- 地址中带着
#
- 使用 hash 地址 模拟完整的 URL;当 hash 地址更新时,页面不会重新加载
- hash 值不会包含在 HTTP 请求中,即 hash 值不会带给服务器
- 如果将地址通过第三方手机 app 分享,若 app 校验严格,则会将地址标记为不合法
history
模式:
const router = new VueRouter({ mode: 'history', routes });
- 地址中没有
#
- history 模式下,
router-link
会守卫点击事件,让浏览器不再重新加载页面 - history 模式下配置
base
选项后,所有的 to
attribute 都不需要写 [基路径] - 有兼容问题,需要后台配置支持
解决 history 模式下的兼容问题:
- 后端人员一个一个地配置路由
- 在服务器上添加一个简单的回退路由。如果 URL 匹配不到任何静态资源,则提供
index.html
页面 - 后端人员通过插件 connect-history-api-fallback 设置路由(基于 node.js 的 express)
① npm i connect-history-api-fallback
、 ② 配置 connect-history-api-fallback
const express = require('express');
const app = express();
app.listen(3000);
const history = require('connect-history-api-fallback');
app.use(history());
app.use(express.static('./public'));
路由传递参数时(对象写法),path
是否可以结合 params
参数一起使用?
答:路由跳转传参时,对象写法不可以只使用 path
属性,否则不会跳转
如何配置 params
参数可传可不传? 配置好后,如果避免传递空字符串?
答:在 params 参数后面添加 ?
即可;可以使用短路算法避免传递空字符串:<router-link :to="{ name: 'Son', params: { msg: '' || null } }"> router </router-link>
路由组件能不能传递 props
数据?
答:可以;可以是 [布尔值]、[对象]、[函数]
路由(英文:router)就是对应关系
2、SPA与前端路由
SPA指的是一个web网站只有唯一的一个HTML页面,所有组件的展示与切换都在这唯一的一个页面内完成。此时,不同组件之间的切换需要通过前端路由实现。
结论:在SPA项目中,不同功能之间的切换,要依赖于前端路由来完成!
3、声明是前端路由
通俗易懂的概念:Hash地址与组件之间的对应关系。
4、前端路由的工作方式
用户点击了页面上的路由链接
导致了 URL 地址栏的 Hash 值发生了变化
前端路由监听
import VueRouter from 'vue-router'
Vue.use(VueRouter); // Vue.use(插件) 在Vue中安装插件
const router = new VueRouter({
// 路由配置
new Vue({
router
1.基本使用
// 路由配置
const router = new VueRouter({