【问题标题】:How to solve Uncaught TypeError: this.filters is not a function ? (vue.js 2)如何解决 Uncaught TypeError: this.filters is not a function ? (vue.js 2)
【发布时间】:2017-07-05 05:18:57
【问题描述】:

我的组件代码是这样的:

<script>
    import _ from 'lodash'
    export default{
        props:['search','category'],
        data(){
            return{
                price_min:'',
                price_max:''
            }
        },
        computed:{
            filters(data){
                const price = {min:this.price_min, max:this.price_max}
                return {q:this.search, category:this.category, sort:data, location:data, price}
            },
        },
        methods:{
            filterProduct: _.debounce(function(data=null){
                    this.$store.dispatch('getProducts', this.filters(data))
            },500)
        }
    }
</script>

我的完整代码是这样的:http://pastebin.com/K7vwU0yY

执行时,控制台出现如下错误:

未捕获的类型错误:this.filters 不是函数

我该如何解决这个错误?

【问题讨论】:

  • 我觉得你应该这样声明:filters:function(data){...}.
  • computed 创建一个数据属性,它并不意味着用作函数。更像是一个数据属性,它根据其他一些变量进行计算。
  • location:data, price 这条线是什么意思?这样我就可以给你推荐一个替代方案。
  • @Alexandru-Ionut Mihai,是一样的。它不起作用
  • @Amresh Venugopal,查看我的完整代码

标签: javascript vue.js laravel-5.3 vuejs2 vue-component


【解决方案1】:
    computed:{
        filters(data) { // the first argument is supposed to be the `this` 
            const price = {min:this.price_min, max:this.price_max}
            return {q:this.search, category:this.category, sort:data, location:data, price}
        },
    },
    methods:{
        filterProduct (data = null) {
           return _.debounce(function (data=null) => {
             this.$store.dispatch('getProducts', this.filters(data))
           },500).call(this, data)
        } 
    }

您使用匿名函数丢失了 vue 组件实例的上下文。 使用箭头函数或将上下文保存在let self = this

在您的情况下,您使用 _.debounce(fn() {}, ms) 返回一个函数,但这样做,您将上下文丢失到 this

所以我将你的去抖代码移动到一个方法中,该方法.calls 是去抖返回的函数回调,this 设置为vue component 实例。

此外,computed 属性不能用作函数。 this.filters(data) 因此仍然会给出类似的错误,因为它是一个属性,就像您可以在 vue 组件实例的 data 中创建的错误一样。改用方法。

【讨论】:

  • 它犯了新的错误。错误:Uncaught TypeError: Cannot read property 'dispatch' of undefined
  • 如果你在错误之前console.log(this),我想你会看到一个lodash实例。您需要将变量保存为 let self = this 并在整个代码中使用 self。
  • 如果您在调度上方进行控制台,this 的值是多少
  • @mosestoh 最新的编辑应该可以正常工作。它没有得到正确的this 上下文。
  • 控制台还是报错,试过了吗?
猜你喜欢
  • 2017-08-30
  • 2017-06-28
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多