前端开发那些事儿

Vue左右滑动入场离场动画效果,以及使用keepAlive缓存页

2020-12-28  本文已影响0人  有点皮的小黄皮

1、vue代码实现代码

之前写好左右滑动入场离场动画效果后,加上keepAlive之后效果总是只有滑进的,返回 离场的没有效果。后面给keep-alive外面包一层div就好了。

<template>
  <div id="app">
    <transition-group :name="transition">
      <div key="keepAlive" v-show="$route.meta.keepAlive">
        <keep-alive>
          <router-view v-if="$route.meta.keepAlive" />
        </keep-alive>
      </div>
      <router-view v-if="!$route.meta.keepAlive" :key="$route.name" />
    </transition-group>
  </div>
</template>
<script>
export default {
  data() {
    return {
      transition: ""
    };
  },
  watch: {
    $route(to, from) {
      if (to.meta.index > from.meta.index) {
        this.transition = "slide-left";
      } else {
        this.transition = "slide-right";
      }
    }
  }
}
</script>
<style>

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.main-box {
  min-height: 100vh;
}

.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  will-change: transform;
  transition: all 300ms;
  position: absolute;
  width: 100%;
  height: 100%;
}
.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);
}
</style>

2、router路由层代码

meta.index 是定义路由层级,方便识别是返回离场还是前进入场。
meta.keepAlive 是用来判断页面是否需要缓存。


/**
 * 页面路由
 */

export default [{
  path: "/",
  name: "Home",
  meta: {
    index: -1,
    keepAlive: true
  },
  component: () => import("./../views/Home.vue"),
  props: true,
  children: []
},{
  path: "/About",
  name: "About",
  meta: {
    index: 0,
    keepAlive: false
  },
  component: () => import("./../views/About.vue"),
  children: []
}];

如有问题,请多多指教~

上一篇下一篇

猜你喜欢

热点阅读