可调用函数可在vue应用程序上全局使用

时间:2019-04-11 06:47:57

标签: vue.js vuejs2

我有将此功能绑定到名为animatecss的CSS动画插件上

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声明为全局变量,但对我来说似乎并不整洁。有什么想法,请帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果您设置

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,以更灵活的方式提供此功能。