What is the solution for the error message "this.filters is not a function" in Vue.js 2?

Here is the code for my component:

<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>

You can view the full code here.

After executing the code, I encountered an error in the console:

Uncaught TypeError: this.filters is not a function

Any suggestions on how to resolve this error?

Answer №1

    computed:{
        filters(data) { // the first argument is expected 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)
        } 
    }

You have lost context to the vue component instance by using an anonymous function. Try using an arrow function or storing the context in a variable like let self = this

In this scenario, using _.debounce(fn() {}, ms) results in losing the reference to this.

To address this issue, I moved the debounce logic inside a method that explicitly sets this to refer to the Vue component instance.

Furthermore, computed properties are meant for returning values based on existing data, not executing functions. Hence, calling this.filters(data) would still cause an error as it's a property rather than a method. Consider using a method instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble accessing portlet resource URL from JavaScript in Liferay 6.2

I have been working with Liferay Portal 6.2 CE GA3 and I am facing an issue where I need to execute a custom portlet resource method from another portlet's JSP file. Below is the code snippet I am currently using. <a href ="#" onclick="myfunctio ...

How can I create spacing between squares in an HTML div element?

Currently, I am working on my project using Laravel 5. I retrieve some integer values from a database and use them to create square divs in HTML. Below is the current output of my work. https://i.stack.imgur.com/sy2ru.png You may notice that there is spa ...

Can anyone point out where the mistake lies in my if statement code?

I've encountered an issue where I send a request to a page and upon receiving the response, which is a string, something goes wrong. Here is the code for the request : jQuery.ajax({ url:'../admin/parsers/check_address.php', meth ...

Prevent clicking through slides on React by disabling the Swiper feature

Is there a way to handle the global document click event (using React hook useClickAway) so that it still fires even when clicking on a slide? For example, think of a circle in the header like an avatar dropdown - when you click on it, a menu pops up. Th ...

DataTables.Net Buttons not appearing in the interface

I have a basic MVC project that utilizes BootStrap4 and dataTables.Net. When the page loads, an Ajax call is made to fetch data for a table. However, despite following the documentation, I'm unable to get the buttons to display on the page. Everything ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

Position of JSON data response is inaccurate

Currently, I have a function that calls an API from the server in the following manner: getDataSet(callback) { request.open('POST', `${apiPath}`); request.setRequestHeader('Content-Type', 'application/x-ww ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

Can Vuejs functions be triggered using a jQuery event trigger?

I am currently attempting to trigger a change event within a Vue component. Within the component template, there is a select element. When I try to use jQuery to trigger a change event on this element, the Vue component does not seem to detect it. Here i ...

Can csrf protection effectively secure data being posted to a server via axios?

In my current project, I am utilizing Laravel but it is not a Vue Single Page Application (SPA) so no routes are being used. Instead, the registration, login, and other form interactions are done through modals using Vue. Axios is being used to send form ...

What could be the reason for the jQuery not displaying JSON data in the console log?

When I put this code into a file named test.html: <html> <head> <title>Test</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"& ...

The error message "TypeError: default is not a function when using vitest" indicates that

I am currently utilizing vitest for unit testing in my Vue application. After writing some tests, I encountered a failure with the error message: 'TypeError: default is not a function'. However, there's no instance of a function called defau ...

Exploring the implementation of useMediaQuery within a class component

Utilizing functions as components allows you to harness the power of the useMediaQuery hook from material-ui. However, there seems to be a lack of clear guidance on how to incorporate this hook within a class-based component. After conducting some researc ...

Execute Function after Gridview Sorting

While working on a gridview within an update panel, I encountered a scenario where the gridview successfully resorts itself upon clicking on the column header. However, post-sorting, I wish to execute a JavaScript function named MyScript. Any suggestions ...

Vue @click event fails to trigger modal display

I'm currently building a Laravel SPA and utilizing Vue.js as the front end framework. I've encountered an issue that I'm struggling to resolve because, in my opinion, there's nothing wrong with my code. All the @click functions within m ...

If the option is 'Gel', use an if statement to console log

I'm trying to console.log the option from the data() function that is equal to 'Gel'. I attempted to use an if statement, but it doesn't seem to be working. Anyone have any ideas on how to make this work? data(){ return { ...

Axe developer tool alert: The <ul> and <ol> elements should only have direct child elements that are <li>, <script>, or <template>

Check out this code snippet. The Li element is built into the <b-navbar> component, but I'm not sure where to locate it in the HTML. <div> <b-navbar type="light" variant="light"> <b-nav-form> < ...

Duplicate the image from a specific div to another div, ensuring that only one clone is created

I'm trying to replicate an image in multiple spots within a frame, but I can only manage to get one instead of many. Can someone please tell me what I'm doing wrong? I am creating a map of terrain where I need to clone images from one div to anot ...

I'm facing an issue with SSRProvider in my NextJs application

My application is developed using NextJs and Typescript, utilizing the react-bootstrap library for creating components. I am facing an issue where I keep receiving an error message stating that When server rendering, you must wrap your application in an &l ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...