Home >Web Front-end >Vue.js >How to pass value from vue subcomponent to parent component
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.
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
<template> <div> <Tree :data="treeData" show-checkbox ref="treeData"></Tree> <Button type="success" @click="submit"></Button> </div> </template>
The function that the event triggers in the subcomponent
submit(){ this.$emit('getTreeData',this.$refs.treeData.getCheckedNodes()); },
2, bind the triggering event in the parent component
<AuthTree @getTreeData='testData'> </AuthTree>
The parent component triggers the function display Data passed by the subcomponent
testData(data){ console.log("parent"); console.log(data) },
Data printed by the console
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
<template> <div> <tree></tree> </div> </template>
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() },
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
<authtree> </authtree>
Function call of the parent component
console.log( this.$refs.authTree.getData());
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!