在我的组件 shoppingCart.vue 文件中,我调用了一个简单的方法:
saveCart : _.debounce(() => {
console.log('hi');
}, 2000),
但我收到错误: Uncaught 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 router?但我试图制作一个 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
我做错了什么?
最佳答案
Error: Uncaught ReferenceError: _ is not defined.
在 shoppingCart.vue
中执行 import _ from 'lodash';
:
<script>
import _ from 'lodash';
export default {
// ...
}
</script>
Uncaught TypeError: this.debounce is not a function at 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"}
关于vue.js - Lodash 引用错误 : _ is not defined in Vue even though it works everywhere else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088526/