vue 页面进出类似APP的滑动效果

实现vue进入返回实现页面的左右滑动效果

在项目开发中,感觉页面的切换很是生硬,仿照原生APP实现进出页面左右滑动的效果

首先要知道当前操作是进入页面还是返回

在 router 里加一项, 类似这样,添加一个meta,用里面的index来判断页面层级

routes: [
    {
      // 默认的首页
      path: '/',
      name: 'Home',
      component: Home,
      meta: {index: 0}
    },
    {
      // 选择城市
      path: '/city',
      name: 'City',
      component: City,
      meta: {index: 1}
    }
]

在app.vue里面进行判断, index值越小代表层级越大, index小则是返回,index大则是进入

export default {
  name: 'App',
  data () {
    return {
      transitionName: ''
    }
  },
  watch: {
    $route (to, from) {
      console.log(to.meta.index, from.meta.index)
      if (to.meta.index > from.meta.index) {
        this.transitionName = 'slide-left'
      } else {
        this.transitionName = 'slide-right'
      }
    }
  }
}

那么 transition 组件的动画名字就根据是进入还是返回来给它对应的动画

 如果有 keep-alive ,那么要把它包裹在 transition 动画组件里面

 

 最后,想要动画效果还是离不开CSS

CSS左滑右滑效果

@keyframes slideInLeft {
    from {
      transform: translate3d(100%, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
    to {
      transform: translate3d(0, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
  }
  @keyframes slideInRight {
    from {
      transform: translate3d(0%, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
    to {
      transform: translate3d(-100%, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
  }
  .slide-left-enter-active{
    position: fixed;
    top: 0;
    left: 0%;
    width: 100vw;
    height: 100vh;
    animation: slideInLeft .2s linear forwards;
  }
  .slide-left-leave-active{
    position: fixed;
    top: 0;
    left: 0%;
    width: 100vw;
    height: 100vh;
    animation: slideInRight .2s linear forwards;
  }
  /*向右滑动*/
  @keyframes slideOutLeft {
    from {
      transform: translate3d(-100%, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
    to {
      transform: translate3d(0%, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
  }
  @keyframes slideOutRight {
    from {
      transform: translate3d(0%, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
    to {
      transform: translate3d(100%, 0, 0);
      position: fixed;
      top: 0;
      left: 0;
      opacity: 1;
    }
  }
  .slide-right-enter-active{
    position: fixed;
    top: 0;
    left: 0%;
    width: 100vw;
    height: 100vh;
    animation: slideOutLeft .2s linear forwards;
  }
  .slide-right-leave-active{
    position: fixed;
    top: 0;
    left: 0%;
    width: 100vw;
    height: 100vh;
    animation: slideOutRight .2s linear forwards;
  }

 

页面切换动画实现了之后,感觉逼格都提高了一些呢。。。哈哈哈哈

你可能感兴趣的:(vue,vue,vue-router,vue路由动画,vue移动端页面切换动画)