vue中使用wowjs实现滑动到可视区域加载动画

需求:当页面向下滚动到可视区域时,动画出现;当页面向上回滚时,动画不会回退。

用到的插件:wow.js+animate.css

wow.js官方文档:https://wowjs.uk/docs.html
animate.css官方文档:https://animate.style/

1、安装插件:

npm install wowjs --save-dev
npm install animate.css --save

2、在main.js全局引入:

import 'animate.css';

3、将wow.js在需要的.vue文件中单独引用。

在vue2中使用wowjs遇到的坑: 这里不推荐全局引入wow.js,我全局引入后,本地环境运行好着,但是打包上线后,报错:Cannot set properties of undefind(setting ‘getPropertyValue’)
最后经过查看wowjs代码,通过console.log(this),发现wowjs中 this对象undefined
发现是严格模式造成的,严格模式下,this是undefined。

import { WOW } from 'wowjs'
  mounted() {
  // wow初始化
    this.$nextTick(() => {
      const wow = new WOW({
        boxClass: 'wow', // default
        animateClass: 'animated', // default
        offset: 150, // default
        mobile: true, // default
        live: false,
        // live为true时,控制台会提示:MutationObserver is not supported by your browser. & WOW.js cannot detect dom mutations, please call .sync() after loading new content.
        callback: function (box) {
          console.log("WOW: animating <" + box.tagName.toLowerCase() + ">")
        }
      });
      wow.init();
    });
  },

wow.js的配置:
参考文档:https://www.dowebok.com/131.html
在这里插入图片描述

offset为0时,设置动画的元素在出现在浏览器可视区域时执行动画

4、使用动画
html:
在这里插入图片描述
css:

.fadeInRight {
  animation: fadeInRight 1s linear 1;
}
@keyframes fadeInRight {
  0% {
    opacity: 0;
    transform: translateX(20px);
  }
  100% {
    opacity: 1;
    transform: translateX(0);
  }
}

至此,动画效果就可以实现啦!!!

报错后的解决思路:

我第一次在main.js中全局引入wow.js,上线后遇到报错
在这里插入图片描述

尝试解决方案一:
刚开始的思路,因为严格模式下,this是undefined,所以移除了use strict就不会报错
尝试方法:
1、在项目根目录新建一个stripStrictLoader.js,并写入以下代码

function StripStrictLoader(content) {
  if (content.includes('use strict')) content.replace(/('|")use strict('|");?/gm, '');
  if (this.cacheable) this.cacheable(true);
  return content;
}

module.exports = StripStrictLoader;

2、在vue.config.js中加入一段代码

const path = require('path')
module.exports = ({
  transpileDependencies: true,
  chainWebpack: config => {
    config.module
      .rule('removeStrictLoader')
      .test(/\.(t|j)sx?$/)
      .enforce('post')
      .use('removeStrictLoader')
      .loader(path.resolve('./stripStrictLoader.js'))
      .end()
  }
})

报错还有,未解决!

尝试解决方案二:
将wow.js放到 public/static/js 目录下,
然后在index.html中直接引入:

<script type="text/javascript" src="./static/js/wow.js"></script>
<script type="text/javascript">
  new WOW().init()
</script>

报错消失!!!可以解决!

尝试解决方案三:
局部引入wow.js,因为它会单独打个js,这样就不会打包在venders里,推荐这种方式!

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值