H
H
Harconnen2020-05-23 12:06:01
Vue.js
Harconnen, 2020-05-23 12:06:01

How to fix Error in callback for watcher?

It took a live search, I found an example, reworked it for myself, in principle everything works, but in the console it shows the error " [Vue warn]: Error in callback for watcher "keywords": "TypeError: this.fetch is not a function" ".
Here is the code:

<template>
    <div class="boundary-align">
        <input
            type="text"
            class="uk-input uk-form-large"
            v-model="keywords"
        />
        <div v-if="results.length > 0">
                    <ul>
                        <li
                            v-for="result in results"
                            :key="result.id"
                            v-html="highlight(result.title)"
                        ></li>
                    </ul>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            keywords: null,
            results: []
        };
    },

    watch: {
        keywords(after, before) {
            this.fetch();
        }
    },

    computed: {
        fetch() {
            axios
                .get("/api/search", { params: { q: this.keywords } })
                .then(response => (this.results = response.data))
                .catch(error => {});
        }
    },

    methods: {
        highlight(text) {
            return text.replace(
                new RegExp(this.keywords, "gi"),
                '<span class="highlighted">$&</span>'
            );
        }
    }
};
</script>

At first, the code was without highlighting " highlight(text) ", and fetch() was written in methods: . Then everything worked without errors, but then added highlighting and computed: - then the error appeared.
How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-05-23
@Harconnen

First <...> fetch() was written in methods

then added <...> computed: - then the error appeared

Put the fetch method where it was.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question