一、前言

1、滚动事件

2、h5 history模式

二、主要内容

1、   (1)使用前度路由,当切换到新路由时,想要页面滚动到顶部,或者是保持原先滚动的位置,就像重新加载页面那样。vue-router的滚动行为,它让你可以自定义路由切换的时候页面如何滚动

但是:这个功能history.pushState 的浏览器中可以使用

  (2)这个滚动行为只能在h5的history模式下使用,在使用滚动行为的时候必须要先将浏览器的hash模式,改成history模式

2、创建一个小例子模拟演示

  (1)目录结构如下

  

  (2).vue文件如下.js文件如下

<template>
<div>关于我页面</div>
</template>
<script type="text/javascript">
export default{
name:'About',
data(){
return { }
} }
</script> <style type="text/css" scoped></style>

About.vue

<template>
<div>
首页页面
</div>
</template> <script type="text/javascript">
export default{
name:'Home',
data(){
return { }
}
}
</script> <style type="text/css" scoped=""></style>

Home.vue

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Home from '@/components/Home'
import About from '@/components/About'
Vue.use(Router) export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path:'/about',
name:'Abut',
component: About
}
]
})

index.js

  (3)hash模式是一上来就加载所有的请求,当你在切换路由的时候,不会再对后端发起情求,不会重载页面

    (2)在index.js中设置为history模式,发现当切换路由的时候,默认还是保持在上一个路由的位置(这个功能浏览器已经帮我们做好了)

  (3)现在要实现,切换路由的时候,页面停留在指定的位置

  (4)在切换路由的时候没有调用这个savedPosition,会跳到上一次加载那个页面的时候滚动到的那个位置

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Home from '@/components/Home'
import About from '@/components/About'
Vue.use(Router) export default new Router({
mode:'history',
scrollBehavior (to, from, savedPosition) {
//只有调用了history.pushState()的时候才会触发这个方法,也就是当我们点击浏览器中的“<-” "->"的时候 //用这个方法实现期望滚动到哪一位置,
// return { x: 0, y: 400 } //判断如果滚动条的位置存在直接返回当前位置,否则返回到起点
//savedPosition只有当用户点击前进后退,或者go(-1)的时候才会调用
console.log(savedPosition)
if(savedPosition){ return savedPosition; }else{
return {x:0,y:200}
} },
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path:'/about',
name:'Abut',
component: About
}
]
})

3、history配合后端的例子

01-使用本地服务器演示(使用npm run build打包编译之后--->cd dist文件下-->执行hs -o -p 8888),可以发现可以看到我们的页面,但是将这个地址复制到一个新的标签中打开出现404

  上面验证了使用history模式必须配合后端

  02-使用node, 在打包编译后的dist文件夹下新建一个server.js如下

const express = require('express')
const http = require('http')
const fs = require('fs')
const httpPort = 8088 //app.use(express.static(path.join(__dirname, 'dist')))
http.createServer((req, res) => {
if(req.url.startsWith('/static/js') || req.url.startsWith('/static/css')){
fs.readFile('.'+req.url, (err,data)=>{
res.end(data)
}) return;
}
fs.readFile('index.html', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.htm" file.')
} res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
}) res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})

启动服务器,将该访问地址拿到一个新的网页中一样可以渲染出来

4、原理:下面模拟了点击a标签变更地址栏的操作,但是必须在服务器环境下才能运行h5的history模式

服务器代码:

const http = require('http')
const fs = require('fs')
const httpPort = 8088 http.createServer((req, res) => { //读取你要渲染的页面
fs.readFile('./03-history.html', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.htm" file.')
} res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
}) res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})

history-server

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<a class="router-link" href="/">Home</a>
<a class="router-link" href="/about">About</a> <div id="router-view"> </div> <script type="text/javascript">
//获取到上面两个a标签对象
var aobj = document.querySelectorAll('a');
var routerView = document.getElementById('router-view'); function Content(href){
switch (href){
case '/':
routerView.innerHTML = '<div>首页</div>';
break; case '/about':
routerView.innerHTML='<div>关于我们</div>'
break;
}
} console.log(location.pathname) //使用window.location.pathname 拿到/url
Content(location.pathname);//让一开始就出现内容 for(var i=0; i<=aobj.length-1;i++){
aobj[i].addEventListener('click',function(e){
e.preventDefault();
var href = e.target.getAttribute('href');
//变更地址栏
history.pushState({},'',href);
Content(href);
})
} </script>
</body>
</html>

5、了解history.pushState()参考MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/History_API

三、总结

Vue-router(基础)_滚动行为和history模式的更多相关文章

  1. [Vue 牛刀小试]:第十三章 - Vue Router 基础使用再探(命名路由、命名视图、路由传参)

    一.前言 在上一章的学习中,我们简单介绍了前端路由的概念,以及如何在 Vue 中通过使用 Vue Router 来实现我们的前端路由.但是在实际使用中,我们经常会遇到路由传参.或者一个页面是由多个组件 ...

  2. Vue Router基础

    路由 安装 vue-router 起步 <router-link to="/foo">Go to Foo</router-link> <router- ...

  3. vue Router——基础篇

    vue--Router简介 vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用. vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路 ...

  4. Vue 路由的编程式导航与history模式

    编程式导航 注意:官方文档写错了 通过javascript跳转 //第一种跳转方式 // this.$router.push({ path: 'news' }) // this.$router.pus ...

  5. Vue技术点整理-Vue Router

    路由 Vue Router 对于单页面应用来说,如果涉及到多个页面的话,就必须要使用到路由,一般使用官方支持的 vue-router 库 一,Vue Router 在项目中的安装引用 1,在页面中使用 ...

  6. vue Router——进阶篇

    vue Router--基础篇 1.导航守卫 正如其名,vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航.有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的 ...

  7. react router @4 和 vue路由 详解(一)vue路由基础和使用

    完整版:https://www.cnblogs.com/yangyangxxb/p/10066650.html 1.vue路由基础和使用 a.大概目录 我这里建了一个router文件夹,文件夹下有in ...

  8. 「vue基础」一篇浅显易懂的 Vue 路由使用指南( Vue Router 上)

    大家好,今天的内容,我将和大家一起聊聊 Vue 路由相关的知识,如果你以前做过服务端相关的开发,那你一定会对程序的URL结构有所了解,我没记错的话也是路由映射的概念,需要进行配置. 其实前端这些框架的 ...

  9. Vue Router的原理及history模式源码实现

    Hash 模式 URL中 # 后面的内容作为路径地址,可以通过location.url直接切换路由地址,如果只改变了#后面的内容,浏览器不会向服务器请求这个地址,会把这个地址 记录到浏览器的访问历史中 ...

随机推荐

  1. Android开发支付集成——支付宝集成

    微信支付传送门:https://www.cnblogs.com/dingxiansen/p/9209159.html 一.支付宝支付 1. 支付宝支付流程图 2. 集成前准备 去蚂蚁金服注册应用获取a ...

  2. Invalid Host header

    这个主要是自己遇到很多次了,每次都去网上查改哪里,这次记到自己这里吧,以后把遇到的vue工具的一些问题都整理到这里 在vue中开发的项目有时候需要到手机上看效果,但是你配好本地端口之后,会出现访问内容 ...

  3. C,java,Python,这些名字背后的江湖!

    还记得高中的时候,有一次我们计算机老师问我们班要不要去参加市里面的C语言比赛,当时还小的我对编程世界压根就一片空白.那时候我就想啊,为什么是C语言,那么A语言,B语言或者是D语言又是什么呢? 后来就到 ...

  4. 我喜欢的vs code快捷键for mac

    mac上的快捷键,尽量是像我用vs studio上靠近. cmd+K+S: 显示快捷键列 cmd+shift+p: 系统配置命令行 cmd+p:项目中文件列表,选择文件 cmd+shift+o:当前文 ...

  5. 996.ICU 写给... 写给年轻的自己

    好久不"水"长文了,随着Github开源项目996.ICU (工作996,生病ICU) (本意是为了指出互联网等早9晚9每周工作6天的不良加班工作制风气不符合法律,是对程序员等技术 ...

  6. Step by Step Recipe for Securing Kafka with Kerberos

    Short Description: Step by Step Recipe for Securing Kafka with Kerberos. Article I found it is a lit ...

  7. IBM developer:Setting up the Kafka plugin for Ranger

    Follow these steps to enable and configure the Kafka plugin for Ranger. Before you begin The default ...

  8. C语言中printf,scanf,puts,%%等输出格式

    #include<stdio.h> int main(void){    int a;    printf("请输入一个整数,程序求取他的最后一位数字:");    s ...

  9. Spark报错

    1. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at com.mysql.jdb ...

  10. Oracle计算两天两个日期间相差的天数

    Oracle计算两天两个日期间相差的天数: select to_date('19930411','yyyymmdd')-to_date('19890507','yyyymmdd') from dual ...