首页 > 解决方案 > 在 Vue 应用程序上全局可用的可调用函数

问题描述

我有这个函数绑定到一个名为的 css 动画插件animatecss

function animateCss(element, animationName, callback) {
  const node = document.querySelector(element)
  node.classList.add('animated', animationName)

  function handleAnimationEnd() {
      node.classList.remove('animated', animationName)
      node.removeEventListener('animationend', handleAnimationEnd)

      if (typeof callback === 'function') callback()
  }

  node.addEventListener('animationend', handleAnimationEnd);
}

有没有办法让它成为一个有效的 Vue 可调用函数,它完全可用于我的 Vue 应用程序,我用它来调用它,例如

animateCss('#el', 'fadeInDown', function(){
    console.log('animation completed');
});

我可以将其window.animateCss声明为全局变量,但对我来说似乎并不整洁。

标签: vue.jsvuejs2

解决方案


如果你设置

Vue.prototype.$animateCss = function(element, animationName, callback) {
  const node = document.querySelector(element)
  node.classList.add('animated', animationName)

  function handleAnimationEnd() {
      node.classList.remove('animated', animationName)
      node.removeEventListener('animationend', handleAnimationEnd)

      if (typeof callback === 'function') callback()
  }

  node.addEventListener('animationend', handleAnimationEnd);
}

在创建您的应用程序之前,您将能够this.$animateCss在您的所有组件中使用。

您可能还想阅读以更灵活的方式提供此功能的(Global) Mixins 。


推荐阅读