子組件 調用父組件方法


這篇文章中介紹了三種方法分別為:
1、子組件通過使用this.parent.xxx (xxx:是你要調用的方法名) 2、子組件通過使用this.emit('xxx') (xxx:是你要調用的方法名,只要方法名不要后面的小括號)
3、父組件把方法名傳給子組件,在子組件里調用這個方法

代碼如下:

1、子組件通過使用this.$parent.xxx
父組件代碼:

<template> <div> //導入子組件名稱標簽 <child></child> </div> </template> <script> //導入子組件路徑 import child from '~/components/dam/child'; export default { components: { //激活子組件 child }, methods: { //將要被調用的方法 fatherMethod() { console.log('測試'); } } }; </script> 

子組件代碼:

<template> <div> <button @click="childMethod()">點擊</button> </div> </template> <script> export default { methods: { childMethod() { //調用父組件方法 this.$parent.fatherMethod(); } } }; </script> 

2、子組件通過使用this.$emit('xxx')
父組件代碼:

<template> <div> //導入子組件名稱標簽,綁定方法名 <child @fatherMethod="fatherMethod"></child> </div> </template> <script> //導入子組件路徑 import child from '~/components/dam/child'; export default { components: { //激活子組件 child }, methods: { //將要被調用的方法 fatherMethod() { console.log('測試'); } } }; </script> 

子組件代碼:

<template> <div> <button @click="childMethod()">點擊</button> </div> </template> <script> export default { methods: { childMethod() { //調用父組件的方法 this.$emit('fatherMethod'); } } }; </script> 

3、父組件把方法名傳給子組件,在子組件里調用這個方法
父組件代碼:

<template> <div> //導入子組件名稱標簽,並把方法名傳給子組件 <child :fatherMethod="fatherMethod"></child> </div> </template> <script> //導入子組件路徑 import child from '~/components/dam/child'; export default { components: { //激活子組件 child }, methods: { //將要被調用的方法 fatherMethod() { console.log('測試'); } } }; </script> 

子組件代碼:

<template> <div> <button @click="childMethod()">點擊</button> </div> </template> <script> export default { //設置props props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { //調用父組件的方法 if (this.fatherMethod) { this.fatherMethod(); } } } }; </script> 

PS:三種方法,只有第一種方法是在路由下使用,使用時可以不用在父組件中間寫 “<child></child>” 、 “import child from '~/components/dam/child';” 和 “components: {child },” ,第一個“<child></child>”可以直接不用寫,后面兩個在使用路由情況下,會在路由里上;
后面兩種方法在使用路由情況下未能觸發父組件的方法(也許是我寫的方法不對,大家直接可以嘗試一下)。
還有就是“<child></child>”這個不是標准的標簽,同時它也是子組件的名字,也就是 child.vue (解釋的不夠標准,請見諒!)




免責聲明!

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



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