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

Challenges with optimization in AngularJS and Angular Material

Currently, I am working on an AngularJS application that utilizes 7 Angular Material tabs. One issue I have encountered is a significant amount of animation lag when switching tabs or opening a md-select element. According to Chrome Developer Tools, the fr ...

Utilizing Vue to properly reference asset paths for background URLs

I recently developed a Vue application and I am currently trying to display an image as a background in a div element. I have found that using the following code snippet accomplishes this: background: url('~../assets/my_image.png'); However, I a ...

PropType missing in 'vue' library within an open-source project

Currently, I am immersed in the world of open source software development focusing on a fascinating NLP tool called doccano. My journey began by tackling the frontend aspect, where I executed the command npm install to gather all essential dependencies. Ho ...

What is the best way to retrieve the page slug within the layout file in Next.js, specifically when using the app folder structure?

In my latest project, I have implemented a nested layout using the new app folder. Within this layout, I have included a header that appears across all pages in the path www.mysite.com/some-slug. One issue I am facing is with the signup button located in t ...

Establish a connection with the hivemq broker using MQTT protocol

Within my app.js file: const mqtt = require('mqtt') const client = mqtt.connect('mqtt://localhost:1883') topic = 'testTopic' client.on('connect', ()=> { client.subscribe(topic) }) client.on(&a ...

Updating an image using AJAX and Flask

I have a situation in HTML where I need to constantly update an image file with the latest images that come in. Below is the Flask code snippet: @app.route('/uploads/update_file', methods=['GET', 'POST']) def update_file(): ...

When fetching data from a parse object, JavaScript displayed [object, Object] as the result

When trying to access information from my parse data, I am able to display user table data on my document without any issues. However, when I attempt to query another object and insert it into an id element using jQuery with functions like text();, html(); ...

I would greatly appreciate some guidance on asp.net and javascript

I am just starting out with JavaScript and facing some challenges. Currently, I'm struggling to develop a Mouseover and mouseout script. Here is my ASPX code: <div> <div id="div_img" style="height: 300px; width: 300px; border: solid 1p ...

What steps should I take to repair my jQuery button slider?

I am facing a challenge with creating a carousel of three images in HTML using jQuery. When the user clicks on the "Next" or "Previous" buttons, I want to scroll through the images one by one. However, I am struggling to hide the other images when one is d ...

CSS Class Returns to Inactive State

One of my tasks involves adding a new class to an image. .bbbLink img { outline: 1px solid #ddd; border-top: 1px solid #fff; padding: 10px; background: #f0f0f0; } When hovering over the image, I apply the following styles, .bbbLink img ...

I am experiencing unexpected results with my Mongoose filter and sort query in Express JS middleware. The output does not match what I am anticipating, and the sorting functionality seems to

This middleware is used for filtering and sorting data. I made some modifications to it, but it's not functioning as expected: const aliasTopMenu = (req, res, next) => { req.query.sort = '-price'; req.query.fields = 'name,price, ...

retrieve file through an ajax call

When I click on a button, I want to send an AJAX download request. I attempted it like this: Here is my JavaScript code: var xhr = new XMLHttpRequest(); xhr.open("GET", "download.php"); xhr.send(); In the download.php file: <? header("Cache-Control: ...

If a checkbox is checked, then the value in the textbox should be multiplied by 0

I'm faced with a challenge involving a non-clickable textbox that is meant to hold a running total. Each time a checkbox is clicked, its value should be added to the total in the textbox. However, I am now struggling to figure out how to perform mult ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

How to resolve a TypeError saying "Object(...) is not a function"?

I've been attempting to display material-ui tabs as a component on another page, but I'm encountering an error that causes the code to break when loading the page with this component. I've tried two different methods of rendering this compo ...

Iterating over an object while omitting certain elements

Is there a way to insert a separator at a specific position in JSX? For example, I have a list that displays text when an item is clicked: https://i.sstatic.net/s71yE.png Here is the code: <Accordion> {items.map((item, index) => ( <Acco ...

The ES6 class Inheritance chain does not properly utilize the instanceof keyword

My curiosity lies in understanding why the instanceof operator fails to work properly for the inheritance chain when there are multiple chains of inheritance involved. (optional read) How does the instanceof operator function? When using obj inst ...

`Incorporating JavaScript for Menu Navigation on the Homepage: Challenges Ahead`

I am attempting to modify the HTML link within the Javascript on the thank you page, but my attempts to change all respective pages' HTML links to index.html/javascript:goTo(XXXX) have been unsuccessful. How can I successfully alter the link to conne ...

Oops! Remember to always `await server.start()` first before using `server.createHandler()` in next.js

An error is popping up when I attempt to check the functionality of Apollo GraphQL. Error: You must await server.start() before calling server.createHandler() Note: Although there is a similar question regarding this issue, it is specific to Express. Error ...

Select2 eliminates every tag except the first one

I am currently utilizing Select2 in Django for handling many-to-many relationships. The best approach I have found to handle all validation constraints is to create related objects through an AJAX request as soon as they are entered into the Select2 tag fi ...