Having trouble with passing props to data() in Vue.js?

I'm facing an issue where I am unable to pass props to data() in my Vue inline template:

<network-index inline-template>
...
<network-list :data="networks"></network-list> 
...
</network-index>

Inside the Index.vue file, here is how I have set it up:

import NetworkList from './List.vue';

export default{

components: {NetworkList},

data(){
            return {
                networks: []                
            }
        },

created(){          

      this.getNetworList();            

   },

 methods{

      getNetworList(){

              axios.post('/network/ajax').then(response => {
                    this.networks = response.data.list;                                            
                });  

      }

    }
}

Below is the List.vue file code where I am encountering a problem:

<template>      
    <div class="network-list">        
        <div class="row row-list" v-for="(network,index) in items" >
            <network-item :data="network" @deleted="remove(index)"></network-item>            
        </div>
    </div>                                  
</template>

<script>

import NetworkItem from './Item.vue';

    export default{

        props: ['data'],

        components: {NetworkItem},

        data(){
            return {       
                items: this.data
            }
        },
        
        methods{
            remove(index){                              
                this.items.splice(index,1);
            }
        }
    };
</script>

While checking the vue console, I noticed that the data in props contains an array with objects, which is the network list and looks fine. However, the items inside data() appears to be empty. I am unsure of what could possibly be causing this issue.

Answer №1

The issue lies in the fact that when the NetworkList component is initially created, the data (networks) array is empty.

The data (networks) array is populated later on by an ajax request triggered by getNetworkList(), but this process occurs after the NetworkList component has already been constructed due to the asynchronous behavior of ajax requests.

To address this issue, you would need to set up a watch to automatically update items when the data changes.

watch: {
   data(val) {
     this.items = val;
   }
}

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

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Troubleshooting Tips for Resolving Problems with VueJS getElementById Bug

I'm currently working with a VueJS single File component that has the following template: <template> <div class="row"> <div class="col-md-12"> <div id="hottable"></div> < ...

Unusual issue encountered in next.js production: ENOENT error - File or directory not found (image cache)

Encountering an issue with my AWS EC2 deployment of next.js. After running npm run build followed by npm run start, everything appears to be functioning correctly. Initially, there are no webp images in the cache as expected. However, I have noticed that t ...

Why is my AngularJS application triggering two events with a single click?

<button id="voterListSearchButton" class="serachButton" ng-click="onSearchButton1Click()">find</button> This button allows users to search for specific information: $scope.onSearchButton1Click = function() { var partId = $("#partIdSearch" ...

Troubleshooting a problem with scrolling functionality while keeping the header in place and ensuring the correct tab is highlighted

I've successfully created a page with a fixed menu that appears when scrolling, and the tabs activate based on their corresponding section IDs. However, I'm encountering some issues: The scrolling behavior is not precise; when scrolling to sec ...

Triggering a gTag Event on the Fly using Google Tag Manager

I implemented a script that triggers a dynamic gTag.js AdWords conversion based on various user interactions on my webpage. Everything was working smoothly until I switched to Google Tag Manager. Now, the code snippet: gtag('event', 'convers ...

What is the method to have the text cursor within a text field start a few pixels in?

I need a text field with the cursor starting a few pixels (let's say 4) from the left-hand side. I am aware that this can be achieved by adjusting the size of the text field using padding, but I am curious if there is a way to resize the text box with ...

Troubles with loading images on Node.js, Express, and EJS powered Bootstrap 5 navbar

Currently, I am in the process of creating a website using express/node.js/ejs. However, I am facing challenges when it comes to constructing a navbar with Bootstrap 5.0. In my app.js file, I have included express.static: app.use(express.static('publi ...

Using async/await with recursion in NodeJS for handling express requests

My code contains a function named GetAllData() that triggers the GetPurchaseData function, which in turn calls itself recursively until all the data is loaded. async function GetAllData(){ console.log("starting loading purchase data"); await G ...

Javascript Parameter

Each time I enter scroll(0,10,200,10); into my code, it seems to output the strings "xxpos" or "yypos" instead of the actual values. I attempted to remove the apostrophes around them, but unfortunately, that did not resolve the issue. scroll = function( ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

Creating GeoJson using JavaScript

Currently, I am retrieving a latitude/longitude array using Ajax $.ajax({ type: "POST", url: '../m/m_share.php', data: 'zone=' + zone, dataType: 'json', success: function(tab) { var i = 0; ...

Expanding Lists in Bootstrap 3: A Step-by-Step Guide

I have been experimenting with Bootstrap's Example accordion code, which can be accessed via this link: http://jsfiddle.net/qba2xgh6/18/ <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel ...

What is the best way to pass JSON data into a JavaScript function?

As a beginner in javascript, I have been struggling to find a solution for my problem for a week. The code example I am working with is shown below (all within an HTML page in the head tag) //example function 1 function randomString(len, charSet) { ...

Utilizing the powerful combination of AngularJS and Node.js functions

I am facing an issue with the key_client variable as it needs to be loaded with an md5 value obtained from a module called nodejs get-mac. Despite my efforts, I have been unable to make it work successfully. The problem seems to be that key_client is alw ...

Does the execution of node.js event handlers occur when the calling stack is clear?

My belief that code related to node.js events is asynchronous was challenged when I came across the following example: var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); emitter.on('foo', function () ...

I need to send a string response retrieved from an earlier API call as a parameter in a new API request

I'm facing a challenge with an API service that requires sending an encrypted string as a payload to their service and receiving an encrypted string response that needs to be decrypted by another service. The issue is that when I receive a string like ...

JQuery's is() function is returning a true value

I am facing a dilemma with a particular string that can either represent text or an anchor tag with text. I have implemented some logic to always return the text in the following way: $(text).is('a') ? $(text).text() : text; The idea behind ...

Unable to view form data in .php file

How can I change the style of my "Submit" button when a user clicks on it to submit the form? The action attribute calls a PHP file, but the data doesn't show up until I remove the onSubmit attribute from the form. However, without it, I cannot use t ...

Encountering a Vue.js error: receiving a 401 Unauthorized response from a Django

Encountering Vue Js error (401 Unauthorized) View Vue Js Error: 401 Image Tools Utilized- Django Rest Framework Vue.js Upon calling the DRF api in Vue.js (using axios), I am facing issues retrieving data. Refer to the code snippet in App.vue below: e ...