uni.app 子元件呼叫父元件的方法並傳遞資料
阿新 • • 發佈:2021-11-25
$refs
子元件 <template> <button>點選我</button> </template> <script> export default { methods: { emitEvent(msg){ console.log('接收的資料--------->'+msg)//接收的資料--------->我是父元件中的資料 } } } </script> 父元件 <template> <div id="app"> <child-a ref="child"></child-a> <!--用ref給子元件起個名字--> <button @click="getMyEvent">點選父元件</button> </div> </template> <script> import ChildA from './components/child.vue' export default { components: { ChildA }, data() {return { msg: "我是父元件中的資料" } }, methods: { getMyEvent(){ this.$refs.child.emitEvent(this.msg); //呼叫子元件的方法,child是上邊ref起的名字,emitEvent是子元件的方法。 } } } </script>
$emit
子元件 <template> <button @click="emitEvent">點選我</button></template> <script> export default { data() { return { msg: "我是子元件中的資料" } }, methods: { emitEvent(){ this.$emit('my-event', this.msg) //通過按鈕的點選事件觸發方法,然後用$emit觸發一個my-event的自定義方法,傳遞this.msg資料。 } } } </script> 父元件 <template> <div id="app"> <child-a @my-event="getMyEvent"></child-a> <!--父元件中通過監測my-event事件執行一個方法,然後取到子元件中傳遞過來的值--> </div> </template> <script> import ChildA from './components/child.vue' export default { components: { ChildA }, methods: { getMyEvent(msg){ console.log('接收的資料--------->'+msg)//接收的資料--------->我是子元件中的資料 } } } </script>
第三種是父元件把方法傳入子元件中,在子元件裡直接呼叫這個方法
子元件 <template> <div> <button @click="childMethod()">點選</button> </div> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { if (this.fatherMethod) { this.fatherMethod(); } } } }; </script> 父元件 <template> <div> <child :fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
具體方法檢視:
https://www.cnblogs.com/hanli-you/p/8011719.html
https://www.cnblogs.com/jin-zhe/p/9523782.html