【轉】vue 子頁面調用父頁面常用方式


方式一

$parent
父組件

<template> <div> <child></child> </div> </template> <script> import child from './child'; export default { components: { child }, methods: { fatherMethod(str) { console.log(str); } } }; </script> 

子組件

<template> <div> <button @click="childMethod">點擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod('hello'); } } }; </script> 

方式二

props
父組件

<template> <div> <child :fatherMethod="fatherMethodOther"></child> </div> </template> <script> import child from './child'; export default { components: { child }, methods: { fatherMethodOther(str) { console.log(str); } } }; </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('hello'); } } } }; </script> 

方式三

$emit
父組件

<template> <div> <child @fatherMethod="fatherMethodOther"></child> </div> </template> <script> import child from './child'; export default { components: { child }, methods: { fatherMethodOther(str) { console.log(str); } } }; </script> 

子組件

<template> <div> <button @click="childMethod">點擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$emit('fatherMethod', 'hello'); } } }; </script> 

第一種不推薦,一般第三種。



作者:lesdom
鏈接:https://www.jianshu.com/p/3b2651529dad
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM