下面是我从 vue 实例调用的一组外部 javascript 函数
// debounce
function debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this, args = arguments;
later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
// -- end debounce
// animate 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);
}
// -- end animate css
和我的 vue 实例
new Vue({
el: '#app',
template: '#search-tpl',
methods: {
onKeyDown: debounce(function(){
animateCss('#searchboxui-wrapper', 'fadeOutDown',function(){
document.querySelector('#searchboxui-wrapper').style.display = 'none';
});
}
}
})
但它总是抛出未定义
,即使我声明 axios package 或 socketio 包,它会抛出未定义
,请问有什么帮助,想法吗?
PS:我使用的是 Vue CLI 3
最佳答案
创建外部 js 文件,例如 externals.js
,使用 import 从此文件导入所有内容或特定函数,并在 Vue 代码中使用它们:
externals.js 中的内容:
// debounce
function debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this, args = arguments;
later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
// -- end debounce
// animate 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);
}
// -- end animate css
export {debounce, animateCss}
VueJS 中的内容:
import {debounce, animateCss} from '../../js/externals.js'
new Vue({
el: '#app',
template: '#search-tpl',
methods: {
onKeyDown() {
debounce(function() {
animateCss('#searchboxui-wrapper', 'fadeOutDown', function() {
document.querySelector('#searchboxui-wrapper').style.display = 'none';
});
});
}
}
});
关于vue.js - 在 vue 实例中调用外部 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691756/