$emit 子組件觸發父組件的方法:
1 <!-- 子組件 --> 2 <template> 3 <div id="child"> 4 <button @click="tryToParent">click</button> 5 </div> 6 </template> 7 <script> 8 export default { 9 name: 'child', 10 methods:{ 11 tryToParent(){ 12 // 通過$emit進行觸發 13 // 第一個參數為父組件監聽的事件名,后續參數為父組件方法的參數 14 this.$emit("toParent","我從子組件傳來") 15 } 16 } 17 } 18 </script> 19 20 <!-- 父組件 --> 21 <template> 22 <div id="parent"> 23 <!-- 監聽child的toParent事件廣播,用fromChild進行處理 --> 24 <child @toParent="fromChild"></child> 25 </div> 26 </template> 27 <script> 28 import child from "./child.vue" 29 export default { 30 name: 'parent', 31 components:{child}, 32 methods:{ 33 fromChild(msg){ 34 console.log(msg); // 點擊子組件的button,這里最終打印出“我從子組件傳來” 35 } 36 } 37 } 38 </script>
$refs 父組件獲取子組件實例,進而調用子組件方法或者直接修改子組件屬性:
1 <!-- 子組件 --> 2 <template> 3 <div id="child"> 4 <div>{{message1}}</div> 5 <div>{{message2}}</div> 6 </div> 7 </template> 8 <script> 9 export default { 10 name: 'child', 11 data(){ 12 return { 13 message1:"", 14 message2:"" 15 } 16 }, 17 methods:{ 18 fromParent(msg){ 19 this.message1 = msg 20 } 21 } 22 } 23 </script> 24 25 <!-- 父組件 --> 26 <template> 27 <div id="parent"> 28 <button @click="toChild">click</button> 29 <child ref="child"></child> 30 </div> 31 </template> 32 <script> 33 import child from "./child.vue" 34 export default { 35 name: 'parent', 36 components:{child}, 37 methods:{ 38 toChild(){ 39 /** this.$refs.child返回child組件實例 **/ 40 41 // 調用子組件的fromParent方法 42 this.$refs.child.fromParent("我從父組件傳遞過來") 43 // 直接修改child的data 44 this.$refs.child.message2 = "啦啦啦" 45 } 46 } 47 } 48 </script>
在復雜的vue應用中,應該用vuex的store來管理跨組件的數據交流,再根據數據的變化觸發相應的方法。