前端路由的核心:改变URL,但是页面不进行整体的刷新。
原理:
1.url的hash:锚点(#), 本质上是改变window.location的href属性.
假设location.href:https://www.runoob.com
location.hash = '/ ’
location.href = ‘https://www.runoob.com/ #/’
location.hash = '/haha ’
location.href = 'https://www.runoob.com/#/haha ’
2.HTML5的history模式:pushState
假设location.href:https://www.runoob.com
history.pushState({},’ ‘,’/haha’)
location.href:‘https://www.runoob.com/haha’
3.HTML5的history模式:replaceState
假设location.href:https://www.runoob.com
history.replaceState({},’’,’/hehe’)
location.href:‘https://www.runoob.com/hehe’
4.HTML5的history模式:go
假设location.href:https://www.runoob.com
history.back() 等价于history.go(-1)回到上一页
history.forward() 则等价于 history.go(1)去到下一页
vue-router
在vue-router的单页面应用中, 页面的路径的改变就是组件的切换
.
使用vue-router的步骤:
1: 创建路由组件router/index.vue
import Vue from 'vue'
import VueRouter from 'vue-router'
//使用路由
Vue.use(VueRouter)
//定义路由
const routers = []
//创建实例
const router = new VueRouter({
routers
})
//导出实例
export default router
2: 挂载到vue实例main.js
import router from './router'
new Vue({
el:'#app',
router,
rendeer:h=>h(App)
})
3: 配置路由映射: 组件和路径映射关系
components/home.vue
<template>
<div>
<h1>首页内容</h1>
</div>
</template>
<script>
export default {
name: 'home'
}
</script>
import Home from '@/components/home'
...
//定义路由
const router = new VueRouter({
{
path:'/home'
component:Home
}
})
4:使用路由: 通过< router-link > 和< router-view >
<template>
<div id="app">
<router-link to="/home">首页</router-link>
<router-view />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
< router-link>: 该标签是一个vue-router中已经内置的组件, 它会被渲染成一个< a>标签.
< router-view>: 该标签会根据当前的路径, 动态渲染出home组件内容.
在路由切换时, 切换的是< router-view>挂载的组件, 其他内容不会发生改变.
默认情况下, 路径的改变使用的URL的hash.如果希望使用HTML5的history模式,在创建router实例的时候配置即可
const router = new VueRouter({
routers,
mode:'history'
})