In Vue2, you can utilize $ref to retrieve information from a child component and transfer it into the parent component's data

Trying to access child components' data in Vue2 and move it into the parent component's data without triggering an event. Saving count:20 from the child component into the parent component in the example below. Please let me know if there are any errors, thank you!

Child Component

<template>
  <div></div>
</template> 
<script>
export default {
  data() {
    return {
      count: 20,
    };
  },
};
</script>

Parent Component

<template>
  <div>
    <child ref="child1"></child>
    {{count}}
</div>
</template> 

<script> import child from './child.vue' 
export default { 
  components: {
    child
  }, 
  data() {
    return{
      count:this.$refs.child1.count
    }
  },
} 
</script>

VSCode warning message:

Property 'count' does not exist on type 'Vue | Element | Vue[] | Element[]'. Property 'count' does not exist on type 'Vue'.

Browser warning message:

[Vue warn]: Error in data(): "TypeError: undefined is not an object (evaluating 'this.$refs.child1')"

Answer №1

It is advisable to follow the Vue framework guidelines when working with data transfer between child and parent components. This can be achieved by using $emit or utilizing a vuex store for centralized state management.

In order to set the count data attribute after the parent component has been mounted, you should wait until that point.

Child Component

<template>
  <div></div>
</template> 
<script>
export default {
  data() {
    return {
      count: 20,
    };
  },
};
</script>

Parent Component

<template>
  <div>
    <child ref="child1"></child>
    {{ count }}
  </div>
</template>

<script>
import Child from "./components/Child";

export default {
  components: {
    Child
  },
  data() {
    return{
      count: 0
    }
  },
  mounted () {
    this.count = this.$refs.child1.count
  }
};
</script>

While the above approach will work, it lacks reactivity. To simplify and make it reactive, consider the following changes:

Updated Child Component

<template>
  <div></div>
</template> 
<script>
export default {
  data() {
    return {
      count: 20,
    };
  },
  watch: {
    count (currentValue) {
      this.$emit('update', currentValue);
    }
  },
  beforeMount () {
    this.$emit('update', this.count)
  }
};
</script>

Updated Parent Component

<template>
  <div>
    <child @update="count = $event"></child>
    {{ count }}
  </div>
</template>

<script>
import Child from "./components/Child";

export default {
  components: {
    Child
  },
  data() {
    return{
      count: 0
    }
  }
};
</script>

For a demo showcasing the updated code in action, click here: https://codesandbox.io/s/interesting-kalam-et0b3?file=/src/App.vue

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

Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have: $('#draw').on('click', 'p', function () { if($(this).ha ...

Go through each item in the array and change its properties

When retrieving data from the database, I receive the following information: "Data": [{ "mainData": [{ "_id": ObjectId("5ab63b22d012ea2bc0bb7e9b"), "date": "2018-03-24" }], "files": [ { "_id": ObjectId("5ab63b22d012ea2bc0bb7e9d"), ...

What is the best way to set up an external site iframe that utilizes PHP as a proxy on my web server without encountering CORS issues?

I came across a tutorial on using curl in php, and here is what I have implemented so far: index.html: <!DOCTYPE html> <html> <head> </head> <body> <iframe src="fetch.php" width="800" height="500"></iframe> </ ...

Guide to modifying CSS properties of an individual element by manipulating class names with JavaScript

I have been searching for an answer to my question without success. I have a unique challenge where I need to change the styles of an h1 element by adding a class based on which radio button is clicked. The issue I'm facing is that when I select a dif ...

Creating numerous hash codes from a single data flow using Crypto in Node.js

Currently, I am developing a Node.js application where the readable stream from a child process' output is being piped into a writable stream from a Crypto module to generate four hash values (md5, sha1, sha256, and sha512). However, the challenge ari ...

Modify the divs in two separate occasions when submitting different forms

Within my form, I have radio buttons located inside div1, a captcha code to be solved in div2, and additional content in div3. My goal is to have div1 replaced by div2 when a radio button is checked and submitted. Then, after completing the captcha in div2 ...

Yaml scripting for BunJs CLI commands

Are there any CLI tools in bun.js that are capable of interpreting Yaml scripts? Similar to how npm processes package.json files in node.js, allowing script definition and execution from the command line interface, but with Yaml being a more readable form ...

I'm encountering an issue where the data in my personalDeatail model's add value is not updating automatically. Can someone please help me

I've been struggling to automatically update the data in model personalDetail.add value when adding two column data. The added data appears correctly in the input box, but it's not updating in personalDetail.add. What am I missing here? Help need ...

bootstrap-vue tabs - reveal specific tab content based on URL anchor tag

For my SPA, I am utilizing bootstrap-vue and currently working on a page where nested content needs to be placed within b-tabs. If given a URL with an anchor (e.g. www.mydomain.com/page123#tab-3), the goal is to display the content under Tab 3. Query: Ho ...

Differences between count() and length() methods in Protractor

When it comes to determining the number of elements inside the ElementArrayFinder (which is the result of calling element.all()), you have two options according to the documentation: $$(".myclass").length, detailed here: This approach involves using ...

The child's status is not displaying correctly

I am in the process of developing a blackjack app and facing an issue with re-rendering hands after the initial deal. I have tried updating the state in App.js and passing it to PlayerHand.js for rendering, but the child component does not refresh despite ...

Implementing dynamic page titles in Vuejs

I have created an application with a header that displays the title of each page. Currently, I am using view-router to define these titles. { path: '/events', name: 'events', component: Events, meta: { title: &a ...

Displaying PHP output within a JavaScript expression

Let's dive into a scenario involving a basic HTML document and some JavaScript that's loaded within it: <!-- doc.html --> <!doctype html> <html lang="en"> <head> <script type="text/javascript" src=" ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

Tips for Sending Emails from an Ionic Application without Utilizing the Email Composer Plugin

I am attempting to send an email from my Ionic app by making an Ajax call to my PHP code that is hosted on my server. Below is the code for the Ajax call: $scope.forget = function(){ $http({ method: 'POST', url: 's ...

What is the best method to retrieve the current time in minutes using the Timer component?

I have integrated the react-timer-hook library into my Next.js application to display a timer. The timer is functioning correctly, but I am encountering an issue where I cannot retrieve the current elapsed time in minutes during the handle form event. My g ...

What is the best way to group a Pie Chart by a string field in a .csv file using dc.js, d3.js, and crossfilter.js in a Node environment?

I've successfully set up several Dimensions and groups, but I'm encountering an issue with a Pie Chart that needs to be grouped based on domain names like bing.com. Each domain name is parsed consistently to xxxx.xxx format and the data is clean. ...

Observable in RXJS, with a pipe that transforms based on a dynamic function

I want to create an observable that gets populated with a custom pipe every time it is called. Let me explain this concept with an example: const myObservable = timer(1000); return myObservable.pipe(getCustomPipe()); function getCustomPipe() { return c ...

Enhancing the functionality of a bootstrap button with the addition of an

My goal is to have a button that opens a URL in a new tab. I've managed to achieve this using window.location.href, but it doesn't open the URL in a new tab. The code I'm working with is written in jQuery and Javascript, and it's part ...