Guide on incorporating Vue components: implementing component 2 within the template of component 1

I'm a Vue beginner and struggling with how to use one component within the template of another or how to combine them in HTML. I've tried looking through the documentation and Stack Overflow but can't seem to figure it out.

Currently, I am using Vue via cdnjs.

For example:

I have a root Vue instance #app. Inside, I've registered two data arrays: one for containers and another for tables within those containers.

Now, in my HTML, I have a container where I want to include a table at a specific place. How do I achieve this? When I try to put the table directly inside the container component, Vue doesn't recognize it as valid and throws an error.

Here is my progress so far:


var app = new Vue({
   el: '#app',
   data: {
      containersList: [{container-object}],
      tablesList: [],
      methods(){}
   },

let container = Vue.component('container',{
   props: ['item'],
   template: '<div class="container">{{ item.data }}</container></div>',

<container v-for="item in containerList></container>

At this point, I have managed to render components, populate them with data, and make everything reactive.

My next challenge is populating containers with tables and potentially nesting tables within tables. Any advice on how to approach this?

My current logic seems to be failing here.


let tableComponent = Vue.component('table-component', {
   props: ['item'],
   template: '<div class="table"></div>'
}
let container = Vue.component('container',{
   props: ['item'],
   template: '<div class="container"><table-component></table-component></div>

UPDATE: Although the rendering appears as expected, I am encountering an error related to the "tablesList" array in the data. It seems that the child component does not have access to it and throws the error "Property or method 'tablesList' is not defined on the instance but referenced during render".

The parent container component has access to it, but the child component does not.

Answer №1

After making some adjustments to your code, I have created a simplified example.

Take a look at the revised code snippet below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <container></container>
    </div>
    <script>
      let tableComponent = Vue.component("table-component", {
        props: ["item"],
        template: '<div class="table">table-component</div>'
      });

      let container = Vue.component("container", {
        props: ["item"],
        template: `<div class="container">
            <div>container</div>
            <table-component></table-component>
          </div>`
      });

      let app = new Vue({
        el: "#app",
        data() {
          return {
            containersList: [],
            tablesList: []
          };
        },
        methods: {
          anyMethod() {
            console.log("test");
          }
        }
      });
    </script>
  </body>
</html>

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

Transforming data from an HTML table into a MySQL database

Is there a way to transfer data from an HTML table created with JavaScript to a SQL database? I have been experimenting with the addRow(tableID) function but it doesn't seem to work. Any suggestions on how to solve this issue? Below is the code snipp ...

Guide to attaching a page content button to a fixed header

I am currently developing a webpage with a sticky header, and I want to include an animated button that moves onto the header when scrolled past. You can check out my code snippet here: https://jsfiddle.net/ykL50pjf/ The specific ID for the button is #t ...

Retrieving form parameters within an EJS template

Hey there! I'm diving into the world of Node.js on my own and hitting a stumbling block that seems simple but is causing me some serious frustration. Despite countless searches on Google, I can't seem to figure it out due to fatigue setting in. I ...

What is the reason for the lack of user data being saved in studio3t?

I'm struggling to identify the issue in my app development process. I'm creating an application that collects user email and password, storing them in a database. The problem lies in the fact that while user passwords are successfully stored, the ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

Creating a rhombus or parallelogram on a canvas can be easily achieved by following these simple

I'm new to working with the canvas element and I want to create some shapes on it. Can someone provide me with guidance on how to draw a Rhombus or Parallelogram on a canvas? Something similar to what is shown in this image: https://i.stack.imgur.c ...

What is the best way to integrate the AWS SDK (Javascript) with VueJS?

As a beginner with AWS, I recently set up some lambdas and downloaded the JS SDK to handle requests in my VueJS project. Additionally, I am utilizing Cognito for authentication purposes. I'm curious about whether it is absolutely necessary to include ...

Using node.js to parse an XML file from a URL and iterate through it to retrieve all the URLs contained within

I am currently utilizing the node module xml2js. The format of my xml file looks like this: <?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl"?> <?xml-stylesheet type="text/css" media="screen" href="some url" ?> ...

Ways to retrieve data from a URL and pass it to JavaScript code

I am currently experiencing difficulties in obtaining the values from an object requested through a link on my website. The issue arises from the fact that I have created a PHP method to retrieve data from the database for the values of a particular objec ...

Fixing the issue: "Tricky situation with JavaScript not working within Bootstrap 4's div tag while JS functions properly elsewhere"

Currently, I'm working on implementing a hide/show function for comments using JavaScript. Fortunately, I was able to find a helpful solution here (thanks to "PiggyPlex" for providing the solution on How can I hide/show a div when a button is clicked? ...

Using Javascript to fetch JSON data from a PHP file hosted on an IIS server, incorporating JSONP with

I have set up an HTML5, JavaScript, and CSS3 https application on Windows IIS (Internet Information Services). The structure of the root directory is as follows: index.html, src/index.js, src/send_payment.php Currently, I am attempting to retrieve a basi ...

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

Performing an Ajax call in the correct order within an MVC framework

One challenge I face is ensuring that my series of Ajax calls to call stored procedures and load partial views always fire in the correct order. Sometimes, they do not fire as expected due to timing issues. How can I guarantee that these Ajax calls execu ...

Identify the index of a list item using a custom list created from buttons

When dealing with a dynamically built list like this: <ul id="shortcuts"> <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li> <li><input type="checkbox" value ...

Struggling with dynamic values and regex while utilizing HTML template strings. Need help overcoming regex challenge

Feeling stuck and seeking advice on improving regex usage. For a one-time substitution, the code below works for replacing a single element like -link-. var testHtmlStr = '<tr>' + '<td class="eve"><div class= ...

Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure: -root | | |-child1 | |-innerChild1 | |-innerChild2 | |-child2 I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example: var depth = getInnerDepth( ...

Guide to deploying a Rails app with Vue on the Heroku free plan

My project consists of a front-end built on Vue.js and a backend developed using Ruby on Rails. Now, I am looking to deploy it on Heroku's Free plan. Can someone provide me with the necessary reference documents or helpful links for guidance? Thank yo ...

Uploading files in React.js using Yii2 API

I am working with react.js (version 15) and I need to upload files using yii2 api. Here is my code: My component in react: import React, { Component } from 'react'; import Header from './Heaader'; /* global $ */ class New ...

Add a static line of names to a JavaScript file

Looking for a way to generate data with the following javascript snippet: for (var l = 0; l < table.length; l +=1) { fs.appendFile('results/Test'+ username +'.csv', var1+i, var2 , function(err) { if(err) { return c ...

Why is it necessary to include 'export' when declaring a React component?

When working with React (ES6), there seems to be two variations that I encounter: class Hello extends React.Component { ... } and sometimes it looks like this: export class Hello extends React.Component { ... } I'm curious about the significance o ...