Vue.js 2 components encountering issue with parent-child relationship due to undefined item

I recently started working with Vue and encountered the error

referenceError: items is not defined
. Can anyone help me figure out why this error is occurring or provide some guidance?

Upon initial inspection of the code, it seems like the issue may be related to the items variable not being properly set in the template.

Here's my code:

<div id="root">
    <task-list></task-list>
    <template id="my-parent">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>id</th>
                </tr>
            </thead>
            <tbody>
                <tr is="task" v-for="item in items" :item="item"></tr>
            </tbody>
        </table>
    </template>

    <template id="my-child">
        <tr>
            <td></td>
            <td>{{ item.name }}</td>
            <td>{{ item.id }}</td>
        </tr>
    </template>

</div>
< script >



Vue.component('task-list', {
  template: '#my-parent',
    data: function() {
        return {
            items: []
        }
    },
    methods: {
        getMyData: function(val) {

            var _this = this;
            $.ajax({
                url: 'vuejson.php',
                method: 'GET',
                success: function(data) {
                    console.log(data);
                    _this.items = data;
                },
                error: function(error) {
                    alert(JSON.stringify(error));
                }
            })

        }
    },
    mounted: function() {
        this.getMyData("0");
    }
});

Vue.component('task', {

    template: '#my-child',
    props: ['item'],

    data: function() {
        return {
            item: {}
        }
    }
});
new Vue({
    el: "#root",

});

< /script >

Answer №1

Check out the updated code snippet below:

<template id="my-child">
    <tr>
        <td>{{ item.name }}</td>
        <td>{{ item.id }}</td>
    </tr>
</template>
<template id="my-parent">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>id</th>
            </tr>
        </thead>
        <tbody>
            <tr is="task" v-for="item in items" :item="item"></tr>
        </tbody>
    </table>
</template>
<div id="root">
    <task-list></task-list>
</div>

Here is the corresponding JavaScript part:

Vue.component('task-list', {
  template: '#my-parent',
  data: function() {
    return {
        items: []
    }
},
methods: {
getMyData: function(val) {

    var _this = this;
    _this.items = [{name: '1.name', id: 1}];
 }
 },
 mounted: function () {
   this.getMyData("0");
}
});

Vue.component('task', {

template: '#my-child',
props: ['item'],

data: function() {
    return {
    }
}
});
new Vue({
el: "#root",

});

Keep learning and experimenting with Vue.js! For helpful resources, check out this jsfiddle link.

If you're just starting out with Vue, tutorials can be a great way to get comfortable with the framework.

Note: When declaring properties like "item", avoid using the same name in your data as well.

Answer №2

It is recommended to define templates outside of the div#root element for better organization and clarity.

<div id="root">
    <task-list></task-list>
</div>
 <template id="my-parent">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>id</th>
                </tr>
            </thead>
            <tbody>
                <tr is="task" v-for="item in items" :item="item"></tr>
            </tbody>
        </table>
    </template>

    <template id="my-child">
        <tr>
            <td></td>
            <td>{{ item.name }}</td>
            <td>{{ item.id }}</td>
        </tr>
    </template>

This separation helps ensure that these templates are not considered part of Vue instance for #root, which does not contain any reference to items.

new Vue({
  el: "#root",
  //no items
});

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

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

Creating a JavaScript array filled with database data using PHP

Below is a snippet of PHP code used to establish a connection to a database: <?php $host = "localhost"; $user = "admin"; $password = ""; $dbname = "test"; $con = new mysqli($host, $user, $password, $dbname) or die ('Could not connect to the d ...

What is the best way to implement rate limiting for asynchronous API calls within a specific timeframe?

I have a project that requires me to make over 500 calls simultaneously from my NodeJS server to a third-party server. The issue is that the third-party server has a restriction of only allowing a maximum of 50 calls per second. Can someone assist me in im ...

Tracing a path with a snapping motion using my thumb

Before we begin, let's take a look at the example below. The functionality of this component should mimic that of an input type range. However, I am facing some challenges in calculating the step value and snapping the thumb onto the trail based on t ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

Experiencing issues with connecting to jQuery in an external JavaScript file

My jQuery formatting in the HTML file looks like this: <!doctype html> <html lang="en"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script> </head> < ...

Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code? <div class="square red"></div> <div class="square blue"> ...

Error code 12030: AJAX request status

When making an ajax XMLHttpRequest using the POST method, I am encountering a readyState of 4 with a status of 12030. It is known that 12030 is a Microsoft-specific state code indicating that the connection was not sustained. However, I have been unable to ...

I am looking to transmit information to the controller using AJAX

ajax console.log(total);//10 console.log(number);//4 var form = { total:total, number:number } $.ajax({ url: 'items/cart/update', type: 'POST', data:form }); Spring MVC controller @ResponseBody @P ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

Retrieve the innerHTML contents from all span elements

I'm having trouble getting the content of all span tags that are child elements of div#parent. So far, I've only been able to retrieve the content of the first one. Can someone please assist me with this? $( document ).ready(function() { ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

What is the best way to start the server when the files are located in separate directories?

I have organized my project into two separate folders, one for the client and one for the server Is there a way to use npm start to simultaneously run both the frontend and backend scripts? Check out the screenshot below: View of Two Folders in my Projec ...

Steps for adding a class to an element in VueJS

https://codepen.io/nuzze/pen/yLBqKMY Here's my issue at hand: I currently have the following list stored in my Vue data: { name: 'Camp Nou', id: 'campNou' }, { name: 'Abran cancha', id: 'abranCancha ...

What process is involved in implementing TCO (Tail Call Optimization) for a recursive anonymous function in ES5?

Is there a way to optimize an anonymous recursive function for tail call optimization, similar to how a named recursive function can be optimized? If such a method exists, please provide explanations on how to achieve it. Below is an example of a recursi ...

Sort through various table columns

I am currently utilizing a data table component from Framework7, which is being generated dynamically with JSON data. My goal is to make the column filter input functional within the table. So far, I have succeeded in implementing the filter for the first ...

Troubles encountered with the search bar filter functionality, implementing JS/JQuery within a Laravel blade template

Currently, I have a blade template containing a search bar for filtering purposes. The issue I'm encountering is that the filtering functionality doesn't seem to work as expected after removing Angular from the page entirely. The page is set up ...

Tips for automatically scrolling mat-select option to the top when mat-select is closed

Is there a way to automatically scroll the mat-select options to the top after closing it? I am faced with a situation where I have numerous options in my mat-select dropdown. If I select an option from the bottom and then close the mat-select, is there a ...

Is it possible for me to save external CDN JavaScript files to my local system?

Normally, I would include scripts from other providers in my application like this: <script src="https://apis.google.com/js/api.js"></script> However, I am considering whether it is feasible to simply open the URL , and then copy and paste th ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...