Having trouble with your computed includes not working in Vue.js? Unsure of how to fix it?

How come when I use "includes" in Vue with my v-model, Vue.js logs an error? However, if I write (.includes("blabla)), everything works fine.

What could be the issue?

Also, how can I return the entire array if the (if) condition will work?

For example, something like this.emojiesByCategory.push() ?

Please assist me with this.

<template>
    <div id="app">
        <div class="emoji_picker">
            <div class="picker_container">
                <input v-model="search">
                <div class="category"
                     v-for="category in categories"
                     :key="`category_${category}`"
                >
                    <span>{{ category }}</span>
                    <div class="emojis_container">
                        <button
                            v-for="(emoji, index) in category_emojis(category)" // ERROR HERE
                            :key="`emoji_${index}`"
                        >
                            {{ emoji }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import data from '../data.json'

export default {
    name: 'App',
    data() {
        return {
            search: "",
            emojiesByCategory: ""
        }
    },
    computed: {
        categories() {
            return Object.keys(data);
        },

        category_emojis: () => (category) => {
            for (let i = 0; i < Object.keys(data[category]).length; i++) {
                if (Object.keys(data[category])[i].includes(this.search)) { // ERROR THERE !!!
                    console.log(Object.values(data[category])[i]) 
            }
            return Object.values(data[category])
        }
    },
}
</script>



// How do I fix this?

My JSON looks like:

{
    "Frequently used": {
        "confused": "😕",
        "neutral_face": "😐",
        "blush": "😊",
        "heart_eyes": "😍"
    },
    // and others
}

Please lend me a hand

Answer №1

Utilizing arrow functions in computed properties may result in the loss of access to this.search. When referencing this.search within an arrow function, it does not point to the Vue instance's data property search, but rather to the parent scope (potentially window in a browser environment), where search is likely undefined.

To simplify:

category_emojis() {
    return (category) => {
        let filteredEmojis = {};

        for (let emoji in data[category]) {
            if (emoji.includes(this.search)) {
                filteredEmojis[emoji] = data[category][emoji];
            }
        }

        return Object.values(filteredEmojis);
    }
}

Additionally, ensure that you initially declared emojiesByCategory as a string within your data. It should be changed to an array as well.

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

What is the best way to break out of a function halfway through?

What are your thoughts on using nested if statements? $scope.addToCart = function () { if (flagA) { if (flagB) { if (flagC) { alert('nononono!'); return; } } } e ...

Is there a way to automatically fill number fields by clicking on radio buttons using a JavaScript function?

Currently, I am facing an issue with a task that involves three elements: 1. Two Number fields (from standard class) that need to be populated dynamically. 2. A Javascript function designed to extract coordinates using geolocator. 3. A radio button which, ...

There was an issue locating a declaration file for the module 'clarifai'

https://i.stack.imgur.com/PgfqO.jpg I recently encountered a problem after installing the Clarifai API for a face recognition project. Despite my efforts, I have been unable to find a solution. When I hover over "import clarifai," I receive the message: ...

Is there a way to create a custom column in Tabulator that displays a calculated value for every row?

Can a custom column be added with a calculated value for each row? For example, if col 1 has the value "3" and col 2 has the value "5", then I want a dynamic col 3 with a sum value of 8. I am utilizing Vue Tabulator. Below is my Table.vue component. <t ...

The hierarchy of CSS in Vue components

I've developed a customized CSS framework to streamline the design process across all my internal projects. The central file is structured as shown below: @import "~normalize.css/normalize.css"; @import "_variables.scss"; @import "_mixins.scss" ...

Tips on how to dynamically update information with Angular

Looking to dynamically update data when a user selects an option from a dropdown menu using the Angular framework This is what I currently have: <div> <button type="button"> {{tests[0].test}} </button> <ul c ...

The initial drag function seems to be dysfunctional in vue-smooth-dnd for vuejs

Check out the code snippet below for a drag and drop section. The div with the class drag-block should be draggable, but it doesn't work on the first attempt; it only drops when we drag it for the second time. https://github.com/kutlugsahin/vue-smoot ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

Accessing props in react-native-testing-library and styled-components is not possible

I defined a styled-component as shown below: export const StyledButton = styled.TouchableOpacity<IButtonProps> height: 46px; width: 100%; display: flex; flex-direction: row; justify-content: center; align-items: center; height: 46px; ...

Tips for refreshing HTML multiple file upload without reloading the page

I am currently working on a feature that involves counting the number of files uploaded. If more than 10 images are uploaded, I want to clear the input field while keeping everything else in the form intact. Everything was working fine until I encountered ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

What is the best way to retrieve attributes from a through table using a query?

I am in the process of creating a straightforward shopping cart system. My structure includes a Cart model, a Product model, and a connection table called CartItems. Here are the associations: models.Cart.belongsToMany(models.Product, { through: 'Car ...

How can jQuery dynamically append query strings to script loads?

After adding the following JavaScript to my page: $("#divExample").append("<script type='text\/javascript' src='\/scripts\/test_code.js'><\/script>"); A request is being made to: http://.../scripts/tes ...

Unlocking the power of popups with Angular

As a beginner in AngularJS, I have encountered an issue where a popup appears when clicking on the "login/signup" button. Now, I want the same popup to appear when clicking on the "upload resume" button as well. Below is the code that is currently working ...

The method element.isDisplayed() is indicating a false value even though the element is visibly present on the screen

element.isDisplayed() is returning false even though the element is visible on the screen, causing issues with clicking on it. I attempted to use the code below, but without success. Actions cursor = new Actions(driver); cursor.moveTo ...

Adaptive Images with jQuery Mobile Listview

I have been experimenting with the classic listview example featuring thumbnails from the jquery mobile documentation. However, when I upload images of different sizes, they do not display properly due to resolution issues. How can this be resolved? Here ...

How to select an unwrapped element using the v-popover component

The v-popover component is commonly used by wrapping an element inside of it, like so: <v-popover offset="0" placement="right"> <span>My awesome span</span> <template slot="popover">My awesome popov ...

"What is the best approach for setting up an Azure Web App to host both an Express static site and API

Setting up an Express app was a breeze for me, but when it comes to deploying it on Azure Web App, I'm hitting some roadblocks! The structure of my app is quite simple: a static web app with its own API. Requests to /website.com/api are forwarded to ...

The Vuejs component I created is failing to display on my Blade View

I can't seem to render my Vuejs component in my blade view. Any idea what I might be doing wrong? The specific component causing issues is named "star-rating". Blade View <div class="container"> <div class="row"> <div class="col- ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...