Lodash ReferenceError:_在Vue中未定义,即使它在其他任何地方都有效

问题描述 投票:1回答:2

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

我究竟做错了什么?

vue.js vuejs2 lodash vue-router debounce
2个回答
8
投票

错误:未捕获的ReferenceError:_未定义。

shoppingCart.vueimport _ 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"}

0
投票

我的解决方案是一个解决方法:

mounted(){
  let that = this;
  let savingCart = _.debounce(() => {
     that.saveCart();
  }, 1000);

  window.events.$on('savingCart', savingCart);
}

这很好用

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.