vue滚动行为

  • scrollBehavior(只在支持history.pushState的浏览器可用)

使用场景:点击浏览器自带的前进或后退键,想让页面滚到顶部,或者是保持原来的滚动位置,vue-router可以做的更好

1.返回上一路由原滚动条位置

例:

import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
export default new Rotuer({
    mode:"history",
    scrollBehavior(to,from,savePosition){
      //saveposition:记录滚动条的坐标,点击前进后退时记录值{x:?,y:?}
        if(saveposition){
            return saveposition;
        }else{
            return {x:0,y:0}
        }
    }
    routes:[
        {
        
         }
    ]
})

2.返回上一路由设置的hash位置

页面上:

<template>
    <div>
          <p @click="goNext()">滚动条返回当前位置</p>
    </div>
</template>
export defauit{
  data(){
      return{
      }
  },
  methods:{
      goNext(){
          let _this=this;
          _this.$router.push("/home#id")
      }
  }
}

路由中:

import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
export default new Router({
    mode:"histtory",
    scrollBehavior(to,from,savePosition){
        if(to.hash){    //判断是否含有hash
          return {selector:to.hash}  //跳转到锚点
        }
    }
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 介绍 vue-router是一个vue插件。其实质是在location.hash、location.replace...
    AmazRan阅读 5,469评论 0 6
  • 一、前言 要学习vue-router就要先知道这里的路由是什么?为什么我们不能像原来一样直接用 标签编写链接哪?...
    浪里行舟阅读 67,841评论 12 203
  • PS:转载请注明出处作者: TigerChain地址https://www.jianshu.com/p/9a7d7...
    TigerChain阅读 64,177评论 9 218
  • 一、前言 要学习vue-router就要知道这里的路由是什么?为什么我们不能像原来一样直接用标签写链接?vue-r...
    圆滚滚1991阅读 2,607评论 0 2
  • 编程式导航 1 .用在可复用的路由视图里面,比如所有的需要跳转到一个文章具体内容的路由,每一次跳转到新路由的时候,...
    skoll阅读 3,833评论 0 1