Ways to send information from Vue instance to nested components

Currently, I am fetching data using AJAX from the Vue instance and trying to pass it onto different components. As I delve deeper into learning Vue.js, I can't help but notice that the documentation seems a bit scattered...

This snippet showcases what my code looks like:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8>">
    <title>mysite</title>
</head>
<body>

<div id="app">
    <parent-component></parent-component>
</div>

<template id="parent-component-template">
    <div id="the-template">
        <div class="the-list">
            <span is="sector-item" v-for="item in sectors" :sector="item"></span>
        </div>
        <button>Button</button>
    </div>
</template>

<template id="sector-item-template">
    <span>
        {{ sector.name }}
    </span>
</template>

<!-- Vue.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>

<script>
    Vue.component('parent-component', {
        template: '#parent-component-template'
    });

    Vue.component('sector-item', {
        props: ['sector'],
        template: '#sector-item-template'  
    });

    let app = new Vue({
        el: '#app',
        data: {
            sectors: [{
                'id': 1,
                'name': 'Industry'
            }]
        }
    });
</script>

</body>
</html>

An issue arises with the following error message:

[Vue warn]: Property or method "sectors" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Where did I go wrong in my implementation?

Answer №1

It seems like there are some incomplete parts in your code. I've made an attempt to replicate what you're aiming for below:

Vue.component('parent-component', {
  props: ['sectors']
});

Vue.component('child-component', {
  props: ['item']
});

new Vue({
  el: '#app',
  data: {
    sectors: [
      {
        'id': 1,
        'name': 'Industry'
      },
      {
        'id': 2,
        'name': 'Education'
      }
    ]
  }
});
.the-list > div {
  padding: 5px;
  border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>

<div id="app">
  <parent-component :sectors="sectors" inline-template>
    
    <div class="the-list">
      <child-component :item="sector" :key="sector.id" v-for="sector in sectors" inline-template>
        <div>
          <span v-text="item.name"></span>
          <button>Button</button>
        </div>
      </child-component>
    </div>
    
  </parent-component>
</div>

The Vue instance has the property sectors, which is passed as a prop to the <parent-component>.

Now, the <parent-component> contains a prop called sectors (which can have a different name) that receives the value of sectors from the main Vue instance. The v-for directive is used to loop through all items of the parent-component prop and pass each item of the array to the <child-component>.

The <child-component> also has a prop named item.

If you want to explore this concept further, feel free to check out this resource here for more information.

I hope this explanation helps clarify things for you.

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

Add the element of surprise. The element must be either a Model, an Association, or an object

Struggling with configuring PostgreSQL with Node.js, I followed this tutorial and encountered an error without any specific details: Here is the stacktrace Unhandled rejection Error: Include unexpected. Element has to be either a Model, an Association or ...

Mastering the art of implementing dynamic template variables in TinyMCE

After exploring the 'full' example and conducting research on the Wiki and moxie forums, I have yet to find a solution. I am attempting to implement what the wiki states is possible, but encountered an issue when replacing the 'staffid' ...

How can I extract the minimum price from this array list using Reactjs?

In my ReactJS project, I have an array list structured like this. I am trying to find the minimum price from this list. For example, if 'totalll' is 100, how can I achieve that? Please advise on how to navigate through the array to retrieve the i ...

Is it possible to switch from kilometers to miles on the distance matrix service in Google Maps?

let distanceService = new google.maps.DistanceMatrixService(); distanceService.getDistanceMatrix({ origins: [sourceLocation], destinations: [destinationLocation], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERI ...

Not adhering to directive scope when transclusion is used, despite explicit instructions to do so

Trying to use a transcluding directive within another controller, but the inner scope isn't being redefined as expected. Despite trying different methods, I can't seem to figure out what's going wrong. The simplified code looks like this: ...

Error message: When attempting to create dynamic inputs in React, an error occurs stating that instance.render is not

I encountered an issue while attempting to create dynamic inputs in React. The error message 'TypeError: instance.render is not a function' keeps popping up. import React, { Component } from 'react'; import Input from '../../Ui/Inp ...

What causes certain files to sporadically duplicate themselves in Visual Studio Code?

While using vscode for NodeJS development, I have noticed that certain files seem to duplicate themselves sporadically. Why is this happening and what steps can I take to resolve it? I am unsure of how to tackle this issue... ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...

Prevent unchecking a checked list item by clicking on it

Is it possible to prevent the user from unchecking a list item once it has been checked? Your assistance is greatly appreciated! $(".collectioncontainer ul li").click(function(){ $('.collectioncontainer ul li.checked').not(this).removeClass( ...

Unexpected addition of values to a list occurs when scrolling through a web element using Selenium

Having recently delved into Python, as well as programming in general, I am eager to extract data from a webelement that updates dynamically with scrolling using Selenium. A particular post on Stack Overflow titled Trying to use Python and Selenium to scro ...

Regular expressions or regex can be used to match the initial letter or letters of various words

Struggling with regex? After searching for an hour, the best solution found was this one. Still unable to crack it though... Here's what I need: Have a JS array that needs to be filtered. The array looks like: [ 'Gurken halbiert 2kg', &a ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

When implementing asynchronous form control validation in Angular 2, several API requests are triggered

Can anyone help me with adding async validation using a FormControl? For every keypress, I am receiving multiple responses and it seems like an extra request is triggered whenever I type or remove a character in the form control. code-snippets.component.t ...

Encountering unhandled promise rejection error with email field in NextJS when using React Hook Form

I am encountering a bizarre issue where, on my form with two fields (name and email), whenever the email field is focused and onSubmit is called, I receive the following error message: content.js:1 Uncaught (in promise) Error: Something went wrong. Please ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

Determine if an object has been submitted in a MEAN / AngularJS application

I am working with an AngularJS frontend and using Express, Node, and MongoDB on the backend. My current setup is as follows: // my data to push to the server $scope.things = [{title:"title", other properties}, {title:"title", other properties}, {titl ...

Is there a quicker method than using document.getElementById('element-id').innerHTML to retrieve content?

Currently, I am developing a user-friendly step-by-step wizard for my website to gather information about custom orders. Utilizing JavaScript, I have been tasked with updating the content of each "page" using the document.getElementById('element-id&ap ...

Rotating an input 90 degrees within a div for unique positioning

I used JavaScript to make an input range vertical, like so: var range_pitch = document.createElement("input"); range_pitch.setAttribute("type", "range"); range_pitch.style.webkitTransform = "rotate(90deg)"; range_pitch.style.mozTransform = "rotate(90deg)" ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...