vue中ref和$refs獲取元素dom、獲取子組件數(shù)據(jù)與方法調(diào)用示例
作用
ref和$refs配合使用可以用于獲取DOM元素或組件實例
特點
查找范圍在當前組件內(nèi),更精確穩(wěn)定,范圍更小
使用
獲取DOM
(1)在目標標簽添加ref屬性
<div ref="demo">測試測試</div>
(2)獲取DOM
通過this.$refs.xxx獲取,獲取到了還可更改此元素樣式等
const demoDom = this.$refs.demo;
獲取子組件實例
(1)在子組件標簽添加ref屬性
<Son ref="sonRef"></Son>
(2)獲取子組件實例
也是通過this.$refs.xxx獲取,獲取到了即可拿到子組件的數(shù)據(jù)和方法
const sonDom = this.$refs.sonRef;
完整例子
父組件代碼(含vue3寫法喔)
<template> <div> <div ref="demo">測試測試</div> <h1 style="color: red;" :onclick="getDemo">點擊獲取demo</h1> <h1 style="color: red;margin-top: 50px;" @click="getSonRef">點擊獲取子組件實例</h1> <Son ref="sonRef"></Son> <div v-if="sonData.das"> <p>{{ sonData.das }}</p> <botton @click="sonData.fun">調(diào)用子組件方法</botton> </div> </div> </template> <script> import Son from './son.vue' export default { components: { Son }, data() { return { sonData: {} } }, methods: { getDemo() { const demoDom = this.$refs.demo; console.log('獲取到的demo的Dom數(shù)據(jù)是===', demoDom); }, getSonRef() { const sonDom = this.$refs.sonRef; this.sonData = sonDom; console.log('獲取到的子組件的實例是===', sonDom); } } } </script> <!-- vue3的寫法 --> <!-- <script setup> import Son from './son.vue' import { ref } from 'vue' // 聲明同名的ref變量即已經(jīng)去獲取了對應(yīng)的dom或?qū)嵗?,相當于?zhí)行了this.$refs.xxx let demo = ref() let sonRef = ref() const getDemo = () => { console.log('獲取到的demo的Dom數(shù)據(jù)是===', demo); } const getSonRef = () => { console.log('獲取到的子組件的實例是===', sonRef); } </script> -->
子組件代碼
<template> <div>子組件</div> </template> <script> export default { data() { return { das: '我是子組件數(shù)據(jù)呀' } }, methods: { fun() { console.log('我是子組件方法呀'); } } } </script>
效果
總結(jié)
到此這篇關(guān)于vue中ref和$refs獲取元素dom、獲取子組件數(shù)據(jù)與方法調(diào)用的文章就介紹到這了,更多相關(guān)vue ref和$refs獲取元素dom內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue純前端實現(xiàn)導(dǎo)出excel中的圖片與文件超鏈接
這篇文章主要為大家詳細介紹了Vue如何純前端實現(xiàn)導(dǎo)出excel中的圖片與文件超鏈接,文中的示例代碼講解詳細,感興趣的小伙伴可以參考一下2025-03-03vue把頁面轉(zhuǎn)換成圖片導(dǎo)出方式(html2canvas導(dǎo)出不全問題)
這篇文章主要介紹了vue把頁面轉(zhuǎn)換成圖片導(dǎo)出方式(html2canvas導(dǎo)出不全問題),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10vue2.x版本中computed和watch的使用及關(guān)聯(lián)和區(qū)別
這篇文章主要介紹了vue2.x版本中computed和watch的使用及關(guān)聯(lián)和區(qū)別,文章圍繞主題展開詳細的內(nèi)容介紹,需要的小伙伴可以參考一下2022-07-07vue雙向數(shù)據(jù)綁定原理分析、vue2和vue3原理的不同點
這篇文章主要介紹了vue雙向數(shù)據(jù)綁定原理分析、vue2和vue3原理的不同點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12解決vue項目使用font-awesome,build后路徑的問題
今天小編就為大家分享一篇解決vue項目使用font-awesome,build后路徑的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09Vue中Object.assign清空數(shù)據(jù)報錯的解決方案
這篇文章主要介紹了Vue中Object.assign清空數(shù)據(jù)報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03