在我的组件shoppingCart.vue文件中,我正在调用一个简单的方法:
saveCart : _.debounce(() => {
console.log('hi');
}, 2000),
但我得到错误:未捕获的ReferenceError:_未定义。
现在得到有趣的部分。如果我将功能更改为例如:
saveCart(){
console.log(_.random(0, 5));
}
一切都有效,我得到了例子:4。为了使它更有趣,我还有一些其他组件使用_.debounce来搜索用户:
findUsers: _.debounce(
function (term)
{
let vm = this;
axios.get('/search', { params: { user: term }})
.then(response => {
vm.updateResult(response.data);
});
}
,500),
它完美无缺。
所以这里有一些背景信息给你。我想我猜测问题在哪里,但我不确定:我正在使用Laravel,我通过bootstrap.js导入Lodash
window._ = require('lodash');
我的组件shoppingCart.vue由Buying.vue调用。 Buying.vue被称为
export default new VueRouter({
mode: 'history',
routes: [
{
path: '/:user/:title',
component: require('./views/buying/Buying'),
},
],
});
也许问题出在某处,因为vue路由器?但我试图制作一个jsfiddle http://jsfiddle.net/gnu5gq3k/,但我的例子适用于这种情况......在我的现实生活中,test2创建了问题......
可能是什么问题呢?你需要什么样的信息才能更好地理解我的问题?
编辑我必须做一些我看不到的简单错误:我将代码更改为:
debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
},
saveCart: this.debounce(() => {
// All the taxing stuff you do
console.log('blubb');
}, 250),
而我不能称自己的功能!
Uncaught TypeError: this.debounce is not a function
at Object
我究竟做错了什么?
错误:未捕获的ReferenceError:_未定义。
在shoppingCart.vue
做import _ from 'lodash';
:
<script>
import _ from 'lodash';
export default {
// ...
}
</script>
未捕获的TypeError:this.debounce不是Object的函数
在构造对象时不能使用this
(该对象尚未创建)。您可以在函数中使用它,因为该代码不会立即执行。
window.a = "I'm window's a";
var myObj = {
a: 1,
b: this.a
};
console.log(myObj); // {a: 1, b: "I'm window's a"}
我的解决方案是一个解决方法:
mounted(){
let that = this;
let savingCart = _.debounce(() => {
that.saveCart();
}, 1000);
window.events.$on('savingCart', savingCart);
}
这很好用