HMVue7.1【前端路由的概念与原理】
1 初始项目
npm i 或 npm install
npm audit fix
npm run serve
2 路由 & 前端路由 & 哈希地址/锚链接
在单页面项目中,url地址与页面上组件之间的对应关系
hash地址即url中的锚链接(#)
锚链接虽然不会导致页面刷新,但会在浏览器中产生历史记录(/前进后退)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<style>
.box {
height: 800px;
}
#b1 {
background-color: pink;
}
#b2 {
background-color: red;
}
#b3 {
background-color: orange;
}
#b4 {
background-color: skyblue;
}
.side-bar {
position: fixed;
top: 0;
right: 0;
background: white;
}
style>
head>
<body>
<div class="side-bar">
<a href="#b1">b1a>
<a href="#b2">b2a>
<a href="#b3">b3a>
<a href="#b4">b4a>
div>
<div class="box" id="b1">div>
<div class="box" id="b2">div>
<div class="box" id="b3">div>
<div class="box" id="b4">div>
body>
html>
url中#及其之后的属于hash地址
3 前端路由的工作方式
4 前端路由的简易实现
初始项目效果:
<template> <div class="app-container"> <h1>App 根组件h1> <a href="#">首页a> <a href="#">电影a> <a href="#">关于a> <hr /> <Home>Home> <Movie>Movie> <About>About> div> template> <script> // 导入组件 import Home from '@/components/Home.vue' import Movie from '@/components/Movie.vue' import About from '@/components/About.vue' export default { name: 'App', // 注册组件 components: { Home, Movie, About } } script> <style lang="less" scoped> .app-container { background-color: #efefef; overflow: hidden; margin: 10px; padding: 15px; > a { margin-right: 10px; } } style>
进行路由案例改造:
<template> <div class="app-container"> <h1>App 根组件h1> <a href="#/home">首页a> <a href="#/movie">电影a> <a href="#/about">关于a> <hr /> <component :is="comName">component> div> template> <script> // 导入组件 import Home from '@/components/Home.vue' import Movie from '@/components/Movie.vue' import About from '@/components/About.vue' export default { name: 'App', data() { return { // 在动态组件的位置,要展示的具体组件的名字,值必须是字符串,默认为home comName: 'Home' } }, created() { //只要当前的 App 组件一被创建,就立即监听 window 对象的 onhashchange 事件,只要url中hash地址变化就会触发这个事件 window.onhashchange = () => { console.log('监听到了hash地址的变化:', location.hash) switch (location.hash) { case '#/home': this.comName = 'Home' break case '#/movie': this.comName = 'Movie' break case '#/about': this.comName = 'About' break } } }, // 注册组件 components: { Home, Movie, About } } script> <style lang="less" scoped> .app-container { background-color: #efefef; overflow: hidden; margin: 10px; padding: 15px; > a { margin-right: 10px; } } style>