The Vue computed property is failing to retrieve the data it needs

I'm having trouble with the computed() property not retrieving data. Data was initialized in the created() property. Am I missing something here? Any guidance on how to resolve this issue would be greatly appreciated.

const randomPlayers = {
    template:
    `
    <input type="text" v-model="search_player">
    <div v-for="player in modPlayers" v-if="list_of_random_players!=null">
        <p>{{player.firstname}}</p>
        <p>{{player.lastname}}</p>
    <div>

    `,
    props: ['data'],
    data (){
        return{
        list_of_random_players: null,
        search_player: null
        }
    },
    created(){
        this.get_random_players()
    },
    computed: {
        modPlayers(){
            return this.list_of_random_players.filter( person => {
              return !this.search_player ||
                ( person.firstname.toLowerCase().indexOf(this.search_player.toLowerCase()) > -1 || person.lastname.toLowerCase().indexOf(this.search_player.toLowerCase()) > -1) 
            })
        }
    },
    methods: {
        get_random_players: function(){
            $.post(
                url:'random_url'
                data: {
                    players: data
                }
            ).done((success)=>{
                this.list_of_random_players: JSON.parse(success)
            })fail((err)=>{
                console.log(err)
            })
        }
    }
}

I am encountering the following errors:

(1)

TypeError: Cannot read property 'filter' of null

(2)

TypeError: this.list_of_random_players.filter is not a function

Answer №1

According to the documentation on Vue, when a Vue instance is created, it incorporates all properties from its data object into Vue's reactivity system. Any changes to these properties will automatically update the view.

The key is to ensure that the data function returns an object, as pointed out by @Sovalina. Make sure to include the return statement and replace null with []:

data() {
    return {

          list_of_random_items: [],
           search_item: []
    }
 },

Alternatively, you can define it without the return statement like a regular object:

data: {
     list_of_random_items: [],
         search_item: []
  }

If your Vue component is used multiple times, it's recommended to use the function approach as described in the first case.

It's important to note that when declaring a component, the data must be a function returning the initial data object. This ensures that each instance created using the same definition has its own separate data. For more information on this topic, refer to this link.

Lastly, don't forget to add a : to methods if it was accidentally omitted.

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 conceal the HTML video controls for multiple videos displayed on a single webpage?

I have a web page that displays a collection of movies generated using a PHP foreach loop. The code snippet looks like this: foreach ($movies as $movie) { $pos = strrpos($movie, '/'); $id = $pos === false ? $movie : substr($movie, $pos ...

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

Load the content of the dialog and transfer variables

After struggling for days, I am still unable to find a solution to my current dilemma. In my database, there are approximately 1300 items each with its own unique "id", a corresponding "name", and a property called "enabled". My goal is to display links t ...

Encountering a 404 Not Found error upon refreshing a page in Vue JS

I'm encountering a "404 Not found" error when I refresh any page on my Vue JS application hosted in Azure Web APP (IIS Server), except the default web page index.html I've followed the rewrite configuration provided in the VueJs official documen ...

Transform a single attribute in an array of objects using angularjs and Javascript to a different value

Within an angularjs controller, the following code is used: var ysshControllers = angular.module('theControllers', []); ysshControllers.controller('CommonController', function($scope, $http, $route) { $scope.dbKey = $route ...

The JavaScript for loop using .appendChild() is inserting the values of the final object, represented as [object object], into the HTML document

$(document).ready(function () { GetDetails(); }); function GetDetails() { let albumlist = document.getElementById("album-list"); $.ajax({ url: '/Store/browseajax', type: 'GET', data: { id: '@ ...

Tips for inserting a DIV and SCRIPT from a single HTML template into a webpage

I'm working with an HTML template that contains a DIV with a button and a script with a function to call when the button is clicked: <div id="CLC_Form"> various text and checkbox inputs go here... <br> <input type="button" ...

Generate fake data for all possible combinations using JSON faker

In my current project, I am in need of creating test data for a JSON schema. I came across this fantastic github resource that has been incredibly helpful: https://www.npmjs.com/package/json-schema-faker#overview Now, how can we expand it to generate all ...

Identify when the Vue page changes and execute the appropriate function

Issue with Map Focus Within my application, there are two main tabs - Home and Map. The map functionality is implemented using OpenLayers. When navigating from the Home tab to the Map tab, a specific feature on the map should be focused on. However, if th ...

AngularJS modal behaving oddly when checkboxes are used

My Angular app is available in this plunker. Upon clicking the button, a modal dialog opens displaying a list of items. Two of these items are pre-checked based on conditions set in the checkbox table input. The following function handles pushing and spl ...

Tips for utilizing the material ui auto-complete search feature

I am in search of an alternative to material-ui-search-bar because it is no longer being maintained. I have been suggested to try using Material UI's auto complete instead. However, from the examples I've seen, it seems like only text field struc ...

Trigger the select dropdown when a key is clicked

I am currently working on a project in react where I am utilizing the Select component from material. When I open the dropdown and press a key on my keyboard, the option starting with that key gets automatically selected. This behavior is also observed in ...

How can I divide a node module bundle file in webpack?

Recently, I developed a Vuejs App for House Plan that includes various optimization techniques. However, I have encountered an issue with two node modules whose sizes exceed 20kb each. As a result, my performance score on Google's Lighthouse test is n ...

Tips for creating a validator function in Angular that only allows whole numbers between 0 and 30, excluding decimals

When a user enters a value between 0 and 30, the input should accept whole numbers like 0, 2, or 20 but not decimal values such as 20.1 or 0.1. I tried using validators min(0) and max(30), but they still allow decimal values. I need a validator that restr ...

Improving the pagination performance in AngularJS

I created an HTML template to showcase member details, along with adding pagination functionality to improve initial load time. Currently, I retrieve 15 members from the server at once and display them, allowing users to navigate through more members using ...

What are some alternative ways to begin a photo album besides always using the first image

I have a gallery with 5 thumbnail images previewed, but there are more photos in the gallery. Instead of cluttering my code and hiding them with CSS, I am seeking an alternative solution. Below is my current HTML code: <div id="start_slides2"> ...

What is the best way to synchronize CouchDB with multiple PouchDB instances in an AngularJS application?

I need help with my Angular project. I'm trying to figure out how to sync multiple PouchDB databases to a single CouchDB instance without losing any data. Can anyone provide some guidance or advice? ...

An issue arises when attempting to integrate ajax with colorbox

I am currently facing an issue with a WordPress plugin designed for playing videos. It seems that the developer who created it is no longer available, and now the play video button has stopped working. Upon further investigation using Firebug, I noticed ...

The execution of the Javascript function is not being carried out

Why is alert("Test1") being executed, but alert("Test2") is not running? P.S. I'm currently not utilizing JSON data. <script> $(document).ready(function() { var param = 10; $.getJSON( 'modules/mod_sche ...

Error: Unable to locate module: cannot find './node_modules/@material-ui/core/IconButton'

Encountering an error in the browser: Error: Failed to compile ./src/components/layout/search/Searchbar.js Module not found: Can't resolve './node_modules/@material-ui/core/IconButton' in 'C:\Users\Ja\Desktop\ ...