vue.js - Lodash 引用错误 : _ is not defined in Vue even though it works everywhere else

标签 vue.js vuejs2 lodash vue-router debouncing

在我的组件 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/

相关文章:

javascript - 如何动态编译添加到 VueJS 模板中的组件?

Laravel 5.4 Vue.JS 组件挂载失败 : template or render function not defined

javascript - 在不同模块的突变中访问 rootState

javascript - 在Lodash.js/Underscore.js 中,如何为每个元素添加索引?

javascript - 如何使用第二个数组中对象的相关属性对对象数组进行排序

javascript - 如果值相等,如何使 lodash sortBy 不排序

javascript - 使用 Vue.js (cdn) 在特定元素上切换显示/隐藏

javascript - VueJS路由相同的组件不触发OWL Carousel

javascript - Vuejs2监听页面滚动失败

javascript - vue3 类处于事件状态时如何切换事件