How to utilize Vue.js method to retrieve child prop?

In my Vue.js project, I have created two components. The main component uses a child component called NoteRenderer, which includes a prop named data_exchange. My goal is to update this prop from the main component when a button is clicked. I attempted to achieve this by writing the following code:

<template>
    <div>
        <h1>Study</h1>
         <button @click="update_nra()">Change NodeRenderer text.</button> 
    </div>
    <nra/>
    <nrb/>
</template>

<script>
import NoteRenderer from '../components/NoteRenderer.vue'

export default {
    components: {
        'nra': NoteRenderer,
        'nrb': NoteRenderer
    },
    methods: {
        update_nra: function() {
            this.nra.exchange_data = "new text";
        }
    }
}
</script>

However, upon execution, I encounter the runtime error

Uncaught TypeError: this.nra is undefined
. How can I properly access and modify the instance nra of the NoteRenderer component within the update_nra() method?

Answer №1

After noticing another answer with code but no explanation, I felt compelled to provide one here.

In Vue, properties are passed to a Component, meaning in your main component you should have a data variable where you change the value and then bind that variable as a property of the sub-component.

It's not considered best practice to access the internals of another component; instead, it's recommended to follow the Vue API.

Keep in mind that properties shouldn't be changed from within a component; the code that passes the property is responsible for any changes.

This method ensures a clear flow of data and results in cleaner code with fewer bugs that are also easier to understand.

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

Supporting multiple types for matching object structures is a feature in Jest

I'm currently working on a test using jest to verify if an object key is either a string or a number. It seems like a basic task, but surprisingly there isn't much guidance in the documentation. Test Example: test('Checking asset structure ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

Unable to host Express app on Firebase functions emulator due to a port conflict with error code EADDRINUSE: address already in use :::3000

Testing the deployment of an express app on Firebase using Firebase functions has presented a challenge for me. Upon running the command firebase serve, I encountered the error EADDRINUSE: address already in use :::3000. Below is my index.js file: const fu ...

Is it possible to integrate Google Analytics with Next.js version 13?

Is there anyone who has successfully integrated Google Analytics with NextJS 13? I tried following the steps outlined in this thread: How to implement Google Analytics with NextJS 13?, but despite doing everything as instructed, I am not seeing any data o ...

Exploring Vue's "is" Attribute with Web Components

I've encountered an issue while trying to utilize a web component that extends an existing element using the "is" attribute tag within Vue. The problem is that Vue takes this attribute and transforms it into a custom element. While I still want Vue t ...

Bringing in a Vue.js component without relying on npm installation or webpack

I'm currently working on integrating this particular component into my project: https://www.npmjs.com/package/vuejs-auto-complete The issue I've encountered is that the restriction against using npm install has posed a challenge. As our project ...

The functionality of the Bootstrap carousel may be compromised when initialized through JavaScript

Why isn't the Bootstrap carousel working in the example below? It starts working when I paste it into .content <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script sr ...

Create a component by dynamically generating HTML content and initializing it

I'm currently working on a Laravel application using VueJS with gulp and browserify. Everything seems to be functioning properly with my vue components when integrated with normal HTML or blade files. The issue arises when attempting to load the HTM ...

Click twice on the editable AngularJS table to wrap each item

As a new learner of Angularjs, I found an existing code example and decided to customize it. My goal was to enable double-click editing for each li item. However, after adding one more li, the functionality did not work as expected. <li ng-dblclick="st ...

Achieving the minimum width of a table column in Material-UI

Currently I am in the process of developing a React website with Material-UI. One query that has come up is whether it's feasible to adjust the column width of a table to perfectly fit the data, along with some extra padding on both ends? Outlined be ...

Exploring the concept of returning objects in jQuery

I'm really trying to grasp the inner workings of how jQuery creates the return object when searching for DOM elements. I've delved into the source code, but I must admit that it's not entirely clear to me yet. So, I'm reaching out here ...

Adjust the position of a textarea on an image using a slider

Currently, I am exploring how to creatively position a textarea on an image. The idea is to overlay the text on the image within the textarea and then use a slider to adjust the vertical position of the text as a percentage of the image height. For instanc ...

Analyzing the path of the cursor

Looking to enhance my tracking capabilities by monitoring mouse movements. I have the ability to capture XY coordinates, but understand that they may vary depending on browser size. Are there any other parameters recommended for accurate results? P.S: Be ...

I am having trouble getting the Express Router delete method to function properly when using mongoose with ES8 syntax

I was working on this code snippet : router.delete('/:id', (req, res) => { Input.findById(req.params.id) .then(Input => Input.remove().then(() => res.json({ success: true }))) .catch(err => res.status(404).json({ success: f ...

Exploring the depths of JSON using @attributes and @association in the realm of JavaScript and AngularJS

Currently, I am working on a project that involves utilizing an API for data retrieval, updates, and deletions. The API in question is the prestashop API. While I have managed to retrieve data and update certain items successfully, I encountered an issue. ...

What is the best way to modify JSON data within a file?

To start, I retrieve a JSON array by using the following JavaScript code: $.getJSON("myJSONfile.json") .done(function(data) { myData = data; }); After storing the data in myData, which is a global variable, I proceed to add more informati ...

Setting a property with a generic type array: Tips and tricks

Currently, I am working on implementing a select component that can accept an array of any type. However, I am facing some challenges in defining the generic and where to specify it. My project involves using <script setup> with TypeScript. Here is ...

Combining the power of ExpressJS with a dynamic blend of ejs and React for an

My current setup involves a NodeJS application with an Express backend and EJS for the frontend. The code snippet below shows an example route: router.get("/:name&:term", function(req, res) { Course.find({ courseName: req.params.name, courseTerm: req.p ...

Output the information retrieved from the Axios call

How can I display data fetched from axios in a table? In my controller: public function index() { return User::latest(); } Inside user.vue: export default { data() { return { users: {}, } }, methods: { loadUsers() { a ...

Optimize your Vue.js application by applying :style to the v-for loop just once

I am currently working on constructing a heatmap table using Vue.js. Instead of relying on jQuery, I have been following a tutorial tailored for jquery which can be found here. Everything seems to be functioning properly, but I am running into issues in ...