Home> Web Front-end> Vue.js> body text

How to pass value from vue subcomponent to parent component

青灯夜游
Release: 2023-01-13 00:45:19
Original
68950 people have browsed it

Methods for vue sub-components to pass values to parent components: 1. The sub-component actively triggers events to pass data to the parent component. 2. Bind ref to the subcomponent and define a function that the parent component can call directly. The parent component registers the subcomponent and then binds the ref and calls the function of the subcomponent to obtain data.

How to pass value from vue subcomponent to parent component

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

1. The child component actively triggers the event and passes the data to the parent component

1. Bind an event and the function triggered by the event on the child component

Subcomponent code

Copy after login

The function that the event triggers in the subcomponent

submit(){ this.$emit('getTreeData',this.$refs.treeData.getCheckedNodes()); },
Copy after login

2, bind the triggering event in the parent component

 
Copy after login

The parent component triggers the function display Data passed by the subcomponent

testData(data){ console.log("parent"); console.log(data) },
Copy after login

Data printed by the console

How to pass value from vue subcomponent to parent component

Second, there is no need to trigger events in the subcomponent (such as clicking a button, create() event, etc.)

This way is much simpler,

1, bind ref

Copy after login

in the subcomponent and then Define a function in the child component, which can be called directly by the parent component. The return value of the function is defined as the data we need.

getData(){ return this.$refs.treeData.getCheckedNodes() },
Copy after login

Then register the sub-component with the parent component and then bind the ref, and call the function of the sub-component to obtain the data

 
Copy after login

Function call of the parent component

console.log( this.$refs.authTree.getData());
Copy after login

Related recommendations:《vue.js tutorial

The above is the detailed content of How to pass value from vue subcomponent to parent component. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn