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

Angular File Sorting Error in Gulp detected

After including .pipe(angularFilesort()) in my gulp script, the task runs wiredep but never proceeds to the default task. It just stops after executing wiredep. However, if I remove .pipe(angularFilesort()), the script works perfectly fine. Can someone h ...

Oops! Looks like something went wrong. The command to install the debug app failed because the emulator could not be launched. This could be due to the fact that no emulators were found

I'm in need of assistance to resolve these issues Encountered an error while trying to install the app. Please ensure that your Android development environment is properly configured: https://reactnative.dev/docs/environment-setup. Error: Command fai ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

What is the process for assigning a serial number to each row in the MUI DataGrid?

Initially, the server is accessed to retrieve some data. After that, additional data is added. While the data does not contain an ID, the form must still display a serial number. const columns: GridColDef[] = [ { field: 'id' ...

What is the best way to retrieve a variable in AngularJS1 after the HTML has been divided into multiple child HTML files?

I have segmented my main HTML page into multiple subpages and included them in the main file. However, it seems that each subpage is referencing different '$scope' variables. I am trying to reference ng-modle="My-model" from one subpage to anothe ...

Sending non-textual data within a JQuery ajax POST request

I have encountered an issue related to sending data from a JavaScript application to a Node.js server for database query purposes. Despite trying to find a solution from various sources, I have been unable to resolve it. Here is the code snippet used to s ...

Retrieve a single document from Firestore and assign it to a variable

While I'm still new to NodeJS, I'm currently working on retrieving a single User document from Firestore. const fs = firebase.firestore(); const usersRef = fs.collection('users'); let findUserByContact = (contact) => { let res ...

The AJAX request is not triggered before the postback when using a LinkButton in ASP

I am facing an issue with running an insert statement using a button in my application. Although it is functional, I have noticed that whenever I click the button, the Page_Load function runs before the ajax statement executes. How can I ensure that the a ...

Executing the Axios Interceptor

Trying to implement the logging feature but struggling to follow the documentation provided at: https://github.com/hg-pyun/axios-logger Even though I am getting the expected results, I am curious about running it in Vue.js similar to the image displayed. ...

What caused the sudden malfunction in the extended Express Request?

Currently, I am utilizing Node v12 along with Express v4.16.4 and Typescript version 3.8.3 within VSCode. This particular snippet of code has remained unchanged for almost 8 months and is utilized in all our routers. export interface ICustomRequest exten ...

Selecting random numbers in React.js

I am working on creating a Netflix Clone and I want to change the banner image every time the page refreshes. I have integrated movie details from TMDb and have an array containing these details. My goal is to select a random number between 0 and 19 and us ...

Adding an image to an event on Vue FullCalendar can be done by utilizing the imageurl property. However, be sure

Currently, I am experimenting with dynamically adding an image to FullCalendar events using Vue. However, in my initial static data test, the image does not display. After conducting numerous researches, this is the approach I have been attempting: <t ...

Encountered an issue with formControlName being undefined during the render process in Angular 2

I encountered an issue while implementing Reactive form validation following the official Angular documentation. The error message "username not defined" is causing trouble in my project. Here's the detailed error: Error: Uncaught (in promise): Error: ...

Deselect a CheckBox along with its corresponding label using VueJS

I am currently working on unchecking a checkbox that is already checked using its label in VueJs. DEMO: new Vue({ el: '#app', data: { checkedNames: [], checkedName: true }, methods: { uncheck: function() { this.check ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...

JavaScript Loading Screen - Issues with window.onload functionality

I am currently working on creating a loading screen for my project. I need to use JavaScript to remove the CSS property "Display: none" from the page, but for some reason, my code is not functioning as expected. The Issue: I discovered that using window. ...

The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like: const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, ...

Encountering an issue while attempting to run a Node.js server on a Mac, receiving the error message "no appropriate image located."

unknown406c8f2d5ecb:proves airrider3$ node tronServer.js [Error: dlopen(/Users/airrider3/Documents/proves/node_modules/now/node_modules/node-proxy/build/Release/nodeproxy.node, 1): no suitable image found. Did find: /Users/airrider3/Documents/proves/n ...

Get a subsection of the array starting from index N up to the final

Is there a way to accomplish this specific transformation? ["a","b","c","d","e"] // => ["c", "d", "e"] I initially thought that using the slice method could work, however.. ["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ] ["a","b ...

When using Webpack, there may be difficulties resolving relative path import of express static files

I am currently developing an Outlook add-in with an Express server running. To ensure compatibility with Outlook Desktop, I need to transpile JavaScript to ES5 using Webpack. Below is the simplified structure of my project: /public /javascripts ssoAu ...