vue子組件向父組件傳值的方法:1、子組件主動觸發事件將數據傳遞給父組件。2、子組件中綁定ref,且定義一個父組件可直接調用的函數,父組件注冊子組件后綁定ref,調用子組件的函數獲取數據。
本教程操作環境:windows7系統、vue2.9.6版,DELL G3電腦。
一,子組件主動觸發事件將數據傳遞給父組件
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()); },
2,在父組件中綁定觸發事件
<AuthTree @getTreeData='testData'> </AuthTree>
父組件觸發函數顯示子組件傳遞的數據
testData(data){ console.log("parent"); console.log(data) },
控制臺打印的數據
二,不需要再子組件中觸發事件(如點擊按鈕,create()事件等等)
這種方式要簡單得多,
1,子組件中綁定ref
<template> <div> <Tree :data="treeData" show-checkbox ref="treeData"></Tree> </div> </template>
然后在子組件中定義一個函數,這個函數是父組件可以直接調用的。函數的返回值定義為我們需要的數據。
getData(){ return this.$refs.treeData.getCheckedNodes() },
然后再父組件注冊子組件后綁定ref,調用子組件的函數獲取數據
<AuthTree ref="authTree"> </AuthTree>
父組件函數調用
console.log( this.$refs.authTree.getData());