yangkaiyangyi / prombles

0 stars 0 forks source link

vue 滚动行为用法,进入路由需要滚动到浏览器底部、头部等等 #10

Open yangkaiyangyi opened 5 years ago

yangkaiyangyi commented 5 years ago

使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。 注意:这个功能只在支持 history.pushState 的浏览器中可用。 解决方案:https://router.vuejs.org/zh-cn/advanced/scroll-behavior.html


const router = new  VueRouter({
       mode: 'history',
       scrollBehavior (to, from, savedPosition) {

            if (savedPosition) { //如果savedPosition存在,滚动条会自动跳到记录的值的地方

                 return savedPosition
           } else{
                 return { x: 0, y: 0}//savedPosition也是一个记录x轴和y轴位置的对象
          }
         },
       routes: [...]
     }
```)
yangkaiyangyi commented 5 years ago

关于使用swiper执行路由组件左右滑动的位置问题? 我想让每个块单独记录滚动条拖动距离。 每次拖动了一个,滑动到其他的时候,其他块的滚动高度是一样的。很郁闷。 有没有哪个参数可以让这个几个块单独记录自己的滚动条高度。切换过去自动切换到这个高度。 另外问下,单独每个块下拉加载怎么弄啊~ //(1) var swiper = new Swiper('.swiper-container', { autoHeight: true, //高度随内容变化 });//效果不大好 、 如果是切换回到顶部 //(滑动页面写上 mounted(){ scrollTo(0,0); }// 或者再swiper中点击时候添加scroll-to

methods: {
      initPage() {
        this.nowIndex = this.$route.path === '/index/one' ? 0 : this.$route.path === '/index/two' ? 1 : this.$route.path === '/index/three' ? 2 : 0;
      },
      tabClick(index) {
        scrollTo(0,0) //tab左右滑动回到顶部,解决swiper页面高度继承的的问题
        this.nowIndex = index;
        // 点击导航按钮时向swiper组件发射index
        this.$root.eventHub.$emit('changeTab', index);
      },
      slideTab(index) {
         scrollTo(0,0) //tab左右滑动回到顶部,解决swiper页面高度继承的的问题
        this.nowIndex = index;
        let router = new VueRouter();
        let href = index === 0 ? '/index/one' : index === 1 ? '/index/two' : index === 2 ? '/index/three' :  '/one';
        // 利用路由的push方法更新路径地址
        router.push(href);
      }