// 參考網址:https://cn.vuejs.org/guide/essentials/template-refs.html#ref-on-component
// 模板引用也可以被用在一個子組件上。這種情況下引用中獲得的值是組件實例:
// 如果一個子組件使用的是選項式 API 或沒有使用 <script setup>,被引用的組件實例和該子組件的 this 完全一致,
// 這意味着父組件對子組件的每一個屬性和方法都有完全的訪問權。
// 這使得在父組件和子組件之間創建緊密耦合的實現細節變得很容易,當然也因此,應該只在絕對需要時才使用組件引用。
// 大多數情況下,你應該首先使用標準的 props 和 emit 接口來實現父子組件交互。
// 有一個例外的情況,使用了 <script setup> 的組件是默認私有的:一個父組件無法訪問到一個使用了 <script setup> 的子組件中的任何東西,
// 除非子組件在其中通過 defineExpose 宏顯式暴露。
<!-- 模板引用 --> <template> <input id="txtName" ref="txtName" value="jay.star"> <el-button type="primary" @click="ShowName()">click</el-button> </template> <script setup> import { reactive, ref, getCurrentInstance, onMounted, computed, toRefs, watch, watchEffect, watchPostEffect, onUpdated, onUnmounted } from "vue"; // 聲明一個 ref 來存放該元素的引用 // 必須和模板裏的 ref 同名 const txtName = ref(null); // 模板引用,根據引用對象獲取值。 function ShowName(){ let ctlId = txtName.value.id; let name = document.getElementById(ctlId).value; alert(name); } // 只可以在組件掛載後才能訪問模板引用 onMounted(() => { //txtName.value.focus() }); // 如果你需要偵聽一個模板引用 ref 的變化,確保考慮到其值爲 null 的情況: watchEffect(() => { if (txtName.value) { console.log("組件已掛載"); txtName.value.focus(); } else { console.log("此時還未掛載,或此元素已經被卸載(例如通過 v-if 控制)"); } }) </script>