1 盡管存在 prop 和事件,有的時候你仍可能需要在 JavaScript 里直接訪問一個子組件(例如,調用子組件的方法)。為了達到這個目的,你可以通過 ref
特性為這個子組件賦予一個 ID 引用。
2 $refs
只會在組件渲染完成之后生效,並且它們不是響應式的。這僅作為一個用於直接操作子組件的“逃生艙”——你應該避免在模板或計算屬性中訪問 $refs
。
父組件
<template> <div id="app"> <button @click="start">點擊</button> <Pirate ref="pirate" msg="加勒比海盜"/> </div> </template> <script> import Pirate from './components/Pirate.vue' export default { name: 'app', components: { Pirate }, methods:{ start(){ this.$refs.pirate.hello(); } } } </script> <style> </style>
子組件
<template> <h3> {{msg}} </h3> </template> <script> export default { props: { msg: { type: String } }, methods: { hello() { console.log("子組件方法"); } } }; </script> <style> </style>
運行效果