路由vue-router的实现原理hash和history

前端路由的核心:改变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'
})
编程式的导航和声明式导航

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值