# 操作 DOM 元素技巧 refs refs快速取得畫面上動元素所使用的、類似JQ快速取得動元素 ## ==使用 ref 定義元素== 這邊使用ref屬性、並定義一個名稱 ```html <h3>使用 ref 定義元素</h3> <input type="text" ref="inpuuRef"> ``` 在 mounted() 生命週期開始寫入 ==$refs== 取得多數 ```javascript= mounted() { console.log(this.$refs); } ``` 這時在log會顯示以定義好的平稱 ![](https://i.imgur.com/P1OdvgS.png) 那如果我們直接要取得Dom元素上面正確的屬性 輸入==this.$refs.inpuuRef== ```javascript= console.log(this.$refs.inpuuRef); ``` 將直接顯示 ![](https://i.imgur.com/ASXvNuM.png) <div class="alert alert-success" role="alert"> 所以我們搭配 jq focus 函式 使用的效果、就會一開始載入畫面時,input 就會有 focus 效果、以下為連接的寫法 </div> ```javascript= mounted() { this.$refs.inpuuRef.focus(); } ``` ## ==使用 ref 取得元件內的資訊== 在JS元件結構為 ```javascript= app.component('card', { data() { return { title: '文件標題', content: '文件內文' } }, ``` 在HTML架構上、card 標籤上 加入==ref==屬性 名稱refClick ```htmlembedded= <h3>使用 ref 取得元件內的資訊</h3> <button type="button" @click="getComponentInfo">取得 元件資訊</button> <card ref="refClick"></card> ``` 那在 點擊 getComponentInfo 事件後、可以指定操作資料架構 title 來做變更 ```javascript= methods: { getComponentInfo() { this.$refs.refClick.title = "已被更新" }, ``` ## ==進階,使用 ref 搭配 Bootstrap==
{"metaMigratedAt":"2023-06-16T10:44:39.256Z","metaMigratedFrom":"YAML","title":"操作 DOM 元素技巧 refs","breaks":true,"contributors":"[{\"id\":\"c05b36ac-d774-4e45-8fc3-5e50c9be5123\",\"add\":1233,\"del\":24}]"}
Expand menu