Vue3中ref的用法舉例總結(避免混淆)
前言
在Vue 3中,ref除了用于處理響應式數(shù)據(jù)外,在 Vue 3 中 ref 還可以用于訪問組件中的 DOM 元素、組件實例以及存儲任何需要在組件中進行狀態(tài)管理的值。下面分別介紹這些用法:
1. 訪問 DOM 元素
通過 ref 可以訪問到在組件中定義的 DOM 元素,例如:input、div、img 等??梢允褂?$refs 屬性訪問到這些元素。
<template> <div> <input ref="myInput" type="text"> <button @click="focusInput">Focus Input</button> </div> </template> <script> import { ref } from 'vue' export default { setup() { const myInput = ref(null) function focusInput() { myInput.value.focus() } return { myInput, focusInput } } } </script>
2. 訪問組件實例
可以使用 ref 訪問到組件的實例,以便在父組件中直接調用子組件中暴露的方法或訪問子組件中暴露的數(shù)據(jù)。
<template> <div> <Child ref="childComponent" /> <button @click="callChildMethod">Call Child Method</button> </div> </template> <script> import Child from './Child.vue' export default { components: { Child }, setup() { const childComponent = ref(null) function callChildMethod() { childComponent.value.myMethod() } return { childComponent, callChildMethod } } } </script>
3. 存儲任何需要在組件中進行狀態(tài)管理的值
除了用于處理響應式數(shù)據(jù),ref 還可以用于存儲任何需要在組件中進行狀態(tài)管理的值,例如:定時器 ID、請求狀態(tài)等等。
<template> <div> <p v-if="isLoading">Loading...</p> <button @click="fetchData">Fetch Data</button> </div> </template> <script> import { ref } from 'vue' export default { setup() { const isLoading = ref(false) const timerId = ref(null) function fetchData() { isLoading.value = true timerId.value = setTimeout(() => { isLoading.value = false clearTimeout(timerId.value) }, 3000) } return { isLoading, fetchData } } } </script>
這些都是 ref 函數(shù)在 Vue 3 中的一些用法,除了處理響應式數(shù)據(jù)之外,它還可以訪問 DOM 元素、組件實例以及存儲任何需要在組件中進行狀態(tài)管理的值,使得 Vue 3 變得更加靈活和方便。
補充:獲取 v-for 遍歷的 DOM 或者 組件
<template> <ul> <li v-for="item in cityList" :key="item.id" :ref="getDom"> {{item.city}} </li> </ul> </template> <script> import { onMounted, reactive} from 'vue'; export default { setup(){ const cityList = reactive([ { city:'武漢', id: '027'}, { city:'南京', id: '025'}, { city:'重慶', id: '023'}, ]); // 1.定義一個空數(shù)組,接收所有的dom const lis = []; // 2. 定義一個函數(shù),往空數(shù)組push dom const getDom = (el) => { lis.push(el); } onMounted(() => { console.log(lis,lis[0]) }) return { cityList, getDom, } } } </script>
總結: 先定義一個空數(shù)組,再定義一個函數(shù)獲取元素,并把該函數(shù)綁定到 ref 上(必須動態(tài)綁定),最后在函數(shù)中可以通過參數(shù)得到單個元素,這個元素一般可以放到數(shù)組中。
總結
到此這篇關于Vue3中ref的用法舉例總結的文章就介紹到這了,更多相關Vue3中ref用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VUE?html5-qrcode實現(xiàn)H5掃一掃功能實例
這篇文章主要給大家介紹了關于VUE?html5-qrcode實現(xiàn)H5掃一掃功能的相關資料,html5-qrcode是輕量級和跨平臺的QR碼和條形碼掃碼的JS庫,集成二維碼、條形碼和其他一些類型的代碼掃描功能,需要的朋友可以參考下2023-08-08編寫Vue項目,如何給數(shù)組的第一位添加對象數(shù)據(jù)
這篇文章主要介紹了編寫Vue項目,如何給數(shù)組的第一位添加對象數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04vue項目報錯Extra?semicolon?(semi)問題及解決
這篇文章主要介紹了vue項目報錯Extra?semicolon?(semi)問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10