Vue  官方提供的动画方式有很多种,可以供大家参考,链接地址如下:

https://cn.vuejs.org/v2/guide/transitions.html

这里,我只列举我使用的,路由在切换时,左滑和右滑效果;具体使用步骤如下:

1.在路由文件中给需要动画效果的路由添加index来区分左右滑效果

    // router/index.js
    {
      path: "/card-goods-index",
      name: "card-goods-index",
      component: () => import("@/components/card-goods/card-list.vue"),
      meta: {
        title: "权益列表",
        index: 1
      }
    },
    {
      path: "/card-package-index",
      name: "card-package-index",
      component: () => import("@/components/card-goods/card-package.vue"),
      meta: {
        title: "卡券包",
        index: 2
      }
    },
    {
      path: "/invalid-card-index",
      name: "invalid-card-index",
      component: () => import("@/components/card-goods/invalid-card.vue"),
      meta: {
        title: "失效券",
        index: 3
      }
    },

2.用 <transition> 给<router-view> 组件添加过渡效果

    <!--app.vue-->
    <transition :name="transitionName">
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive">
          <!-- 这里是会被缓存的视图组件-->
        </router-view>
      </keep-alive>
    </transition>

3.在data中设置默认的动画样式

//app.vue   
  data() {
    return {
      url: '',
      transitionName: 'slide-left'//默认动画
    };
  },

4.在css中编写动画

/*app.vue  的style*/
.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  will-change: transform;
  transition: all 500ms;
  position: absolute;
}

.slide-right-enter {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}

.slide-right-leave-active {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.slide-left-enter {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.slide-left-leave-active {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}

5.在watch中监听路由切换,并根据切换路由的index大小设置动画样式

  watch: {
    '$route'(to, from) {
      //页面切换动画
      console.log(to)
      let toName = to.name

      const toIndex = to.meta.index
      const fromIndex = from.meta.index

      this.transitionName = toIndex < fromIndex ? 'slide-right' : 'slide-left'
    }
  },

 

经过上面几部,页面切换左右滑动的动画效果已经实现了

Logo

前往低代码交流专区

更多推荐