vue子組件向父組件傳值的方法:1、子組件主動(dòng)觸發(fā)事件將數(shù)據(jù)傳遞給父組件。2、子組件中綁定ref,且定義一個(gè)父組件可直接調(diào)用的函數(shù),父組件注冊(cè)子組件后綁定ref,調(diào)用子組件的函數(shù)獲取數(shù)據(jù)。
本教程操作環(huán)境:windows7系統(tǒng)、vue2.9.6版,DELL G3電腦。
一,子組件主動(dòng)觸發(fā)事件將數(shù)據(jù)傳遞給父組件
1,在子組件上綁定某個(gè)事件以及事件觸發(fā)的函數(shù)
子組件代碼
<template> <div> <Tree :data="treeData" show-checkbox ref="treeData"></Tree> <Button type="success" @click="submit"></Button> </div> </template>
事件在子組件中觸發(fā)的函數(shù)
submit(){ this.$emit('getTreeData',this.$refs.treeData.getCheckedNodes()); },
2,在父組件中綁定觸發(fā)事件
<AuthTree @getTreeData='testData'> </AuthTree>
父組件觸發(fā)函數(shù)顯示子組件傳遞的數(shù)據(jù)
testData(data){ console.log("parent"); console.log(data) },
控制臺(tái)打印的數(shù)據(jù)
二,不需要再子組件中觸發(fā)事件(如點(diǎn)擊按鈕,create()事件等等)
這種方式要簡(jiǎn)單得多,
1,子組件中綁定ref
<template> <div> <Tree :data="treeData" show-checkbox ref="treeData"></Tree> </div> </template>
然后在子組件中定義一個(gè)函數(shù),這個(gè)函數(shù)是父組件可以直接調(diào)用的。函數(shù)的返回值定義為我們需要的數(shù)據(jù)。
getData(){ return this.$refs.treeData.getCheckedNodes() },
然后再父組件注冊(cè)子組件后綁定ref,調(diào)用子組件的函數(shù)獲取數(shù)據(jù)
<AuthTree ref="authTree"> </AuthTree>
父組件函數(shù)調(diào)用
console.log( this.$refs.authTree.getData());