vue子组件向父组件传值的两种方法

8,995 阅读1分钟

一、子组件主动触发事件将数据传递给父组件 1、在子组件上绑定某个事件以及事件触发的函数子组件代码

<template>
<div>
    <Tree :data="treeData" show-checkbox ref="treeData"></Tree>
    <Button type="success" @click="submit"></Button>
</div>  
</template>

事件在子组件中触发的函数:

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

在父组件中绑定触发事件:

<AuthTree  @getTreeData='testData'></AuthTree>

父组件触发函数显示子组件传递的数据:

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

二、不需要再子组件中触发事件(如点击按钮,create()事件等等)

这种方式要简单得多,子组件中绑定ref

<template>
<div>
<Tree :data="treeData" show-checkbox ref="treeData"></Tree>
</div>  
</template>

然后在子组件中定义一个函数,这个函数是父组件可以直接调用的。函数的返回值定义为我们需要的数据。

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

然后再父组件注册子组件后绑定ref,调用子组件的函数获取数据:

<AuthTree ref="authTree"></AuthTree>

父组件函数调用:

this.$refs.authTree.getData()