Rendering child components in Vue.js with access to parent data

I have a main component in Vue.js with the following structure:

<template>
<ul class="list-group">
    <li class="list-group-item" v-for="item in items">
        <div class="row">
            <div class="col-md-6">
                {{ item.title }}
            </div>
            <div class="col-md-6 text-right">
                <a href="#" class="btn btn-primary btn-sm">
                    <span class="glyphicon glyphicon-pencil"></span>
                </a>
                <a href="#" class="btn btn-success btn-sm">
                    <span class="glyphicon glyphicon-link"></span>
                </a>
                <a href="#" class="btn btn-danger btn-sm">
                    <span class="glyphicon glyphicon-remove"></span>
                </a>
            </div>

            <div class="col-md-12">
                <preview></preview>
            </div>
        </div>
    </li>
</ul>
</template>

The script section:

<script>

import Preview from './Preview.vue';

export default {

    data() {
        return {
            items: '',
            template: []
        }
    },

    created() {
        this.fetchItems();
        this.$on('preview-build', function (child) {
            console.log('new preview: ')
            console.log(child)
        })
    },

    components: {
        Preview
    },

    methods: {

        fetchItems: function () {
            var resource = this.$resource('api/preview');

            resource.get({}).then((response) => {
                this.items = response.body.item;
            }, (response) => {
                console.log('Error fetching tasks');
            }).bind(this);
        },

    }

 }
 </script>

The "preview" child component has a template structure similar to {{ item.title }}. It loads correctly but does not render.

I'm unsure if this is possible in Vue 2.0. If anyone has encountered the same issue and has a solution, I would appreciate the help.

EDIT (thank you Patrick):

<template>
   <textarea rows="20" class="form-control">
     {{ template.content }}
   </textarea>
</template>

<script>
    export default {

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

        created() {
            this.fetchTemplate();
        },

        methods: {

            fetchTemplate: function () {
                var resource = this.$resource('api/preview');

                resource.get({}).then((response) => {
                    this.template = response.body.template;
                }, (response) => {
                    console.log('Error fetching template');
                }).bind(this);
            },

        }

    }
</script>

This is the content of Preview.vue, which is similar to Item.vue content. Just to clarify:

The template data is retrieved from a database as pre-defined HTML content containing {{ item.title }} and other placeholders. I want this to be rendered with specific content from the item.

Answer №1

When working with Vue.js, components are unable to directly access data from their parent components. If you wish for the preview component to render the {{ item.title }}, you will need to pass the item down to it as a prop. This means in the preview.vue file, you need to declare it like so:

export default {
    ...
    props: ['item']
}

Subsequently, in the template of the parent component, you can use v-bind to bind the item prop to an item from the parent component's items array:

<li class="list-group-item" v-for="item in items">
    ...
    <preview v-bind:item="item"></preview>
    ...
</li>

Now the preview component has access to an item that it can render in its template as if it were a part of the data object.

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

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

Implementing data updates in Vue.js within a Mongoose database, along with making API

I've encountered an issue where I need to update a count variable representing the votes each video receives after using GET and POST functions to retrieve and save URLs in my database. Additionally, I'm looking to disable the voting button once ...

Having difficulties including the Stack Overflow website within an iframe

I've been attempting to embed the Stack OverFlow website into an HTML page using an iFrame, but I'm running into some issues. Oddly, when I tried embedding my other two websites, they displayed correctly, but Stack OverFlow is not showing up on m ...

Is there a way to determine the number of options required for a select tag to become scrollable?

Please review these two <select> elements: <select> <option>one</option> <option>one</option> <option>one</option> <option>one</option> <option>one</option> <option&g ...

What is the correct way to include bootstrap.min.js from node modules into a Vue CLI project?

Currently, I am utilizing vue cli for my project. After installing Bootstrap with the command npm install bootstrap, I managed to successfully import @import "../node_modules/bootstrap/dist/css/bootstrap.min.css" ; in a Vue component. However, despite in ...

Check if jQuery condition is met for classes that match exactly

The PHP echo statement below contains the code. The brackets are empty, but I can guarantee that the statement inside, which modifies CSS, works - except for one issue. I want it to only target elements with a class attribute equal to "zoom" or "zoom firs ...

Having trouble with displaying the modal dialog in Twitter Bootstrap 3?

There seems to be an issue with my Twitter Bootstrap modal as it is not rendering the dialog box correctly, and I'm puzzled about the reason behind this. HTML <p class="text-center btn-p"><button class="btn btn-warning" data-toggle="modal" ...

Uncaught Node.js Error Event Handling

Hello everyone, I'm new to this and currently working on writing a code that utilizes node's event emitter. Take a look at the code snippet below: var EventEmitter = require('events').EventEmitter; var errors = require('./errors&a ...

Sharing details of html elements using ng-click (AngularJS)

I am currently exploring options to enable users to click on a "open in new tab" link, which would essentially transfer that HTML element into a fresh window for their convenience. I am seeking advice on how to achieve this. At the moment, I am able to la ...

A guide on accessing JavaScript files from the components directory in a React Native iOS application

I am encountering difficulty in accessing the components folder within my React Native Project on IOS. The error message I am receiving is: Unable to resolve module ./Login from ....../ReactNative/ReactNativeProject/components/App.js: Unable to find ...

The data from my API is not showing up in my React application

Im working on a project where I am trying to retrieve an image of a recipe card from and display it on my react.js application. However, I am encountering difficulties in getting the API data to show up on the page when running the code. Any assistance wo ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

Can you provide a basic illustration of how routes are implemented in AngularJS?

After searching through numerous examples of using Routes with Angular, I have unfortunately not been able to find a working solution. Even the example provided in the official guide did not work properly (clicking on it resulted in a wrong URL that did no ...

Looking to retrieve the value of a selected checkbox within a horizontally laid out HTML table

Trying to extract values from a table with a horizontal header when checkboxes are selected. The goal is to retrieve the values of the selected column for all rows. Code snippet provided below. <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Steps for showcasing the data entered in the input box

I am looking to enhance my skills in working with Angular and JavaScript. I would greatly appreciate any feedback on the issue I am facing here. My goal is for the text box input to display: "hello {name} , would you like to play a game? However, curr ...

Trigger a specific directive instance through a function call when a key is pressed on the

Is it possible to trigger a specific directive instance's function when a global keyboard shortcut is pressed and it has the class "focused" based on ng-class? Below is some template code: home.html <body ng-controller="SampleController"> ...

After the decimal point, there are two digits

My input field is disabled, where the result should be displayed as a product of "Quantity" and "Price" columns ("Quantity" * "Price" = "Total"). However, I am facing an issue where the result often displays more than 2 digits (for example: 3 * 2.93), desp ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

Listening for changes in class property values in TypeScript with Angular involves using the `ngOnChanges`

Back in the days of AngularJS, we could easily listen for variable changes using $watch, $digest... but with the newer versions like Angular 5 and 6, this feature is no longer available. In the current version of Angular, handling variable changes has bec ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...