Vue中ref和$refs的介紹以及使用方法示例
前言
在JavaScript中需要通過document.querySelector("#demo")來獲取dom節(jié)點(diǎn),然后再獲取這個(gè)節(jié)點(diǎn)的值。在Vue中,我們不用獲取dom節(jié)點(diǎn),元素綁定ref之后,直接通過this.$refs即可調(diào)用,這樣可以減少獲取dom節(jié)點(diǎn)的消耗。
ref介紹
ref被用來給元素或子組件注冊引用信息。引用信息將會(huì)注冊在父組件的 $refs對象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向該子組件實(shí)例
通俗的講,ref特性就是為元素或子組件賦予一個(gè)ID引用,通過this.$refs.refName來訪問元素或子組件的實(shí)例
<p ref="p">Hello</p> <children ref="children"></children>
this.$refs.p this.$refs.children
this.$refs介紹
this.$refs是一個(gè)對象,持有當(dāng)前組件中注冊過 ref特性的所有 DOM 元素和子組件實(shí)例
注意: $refs只有在組件渲染完成后才填充,在初始渲染的時(shí)候不能訪問它們,并且它是非響應(yīng)式的,因此不能用它在模板中做數(shù)據(jù)綁定
注意:
當(dāng)ref和v-for一起使用時(shí),獲取到的引用將會(huì)是一個(gè)數(shù)組,包含循環(huán)數(shù)組源
<template>
<div>
<div ref="myDiv" v-for="(item, index) in arr" :key="index">{{item}}</div>
</div>
</template>
<script>
export default {
data() {
return {
arr: ['one', 'two', 'three', 'four']
}
},
mounted() {
console.log(this.$refs.myDiv)
},
methods: {}
}
</script>
<style lang="sass" scoped>
</style>

實(shí)例(通過ref特性調(diào)用子組件的方法)
【1】子組件code:
<template>
<div>{{msg}}</div>
</template>
<script>
export default {
data() {
return {
msg: '我是子組件'
}
},
methods: {
changeMsg() {
this.msg = '變身'
}
}
}
</script>
<style lang="sass" scoped></style>
【2】父組件code:
<template>
<div @click="parentMethod">
<children ref="children"></children>
</div>
</template>
<script>
import children from 'components/children.vue'
export default {
components: {
children
},
data() {
return {}
},
methods: {
parentMethod() {
this.$refs.children //返回一個(gè)對象
this.$refs.children.changeMsg() // 調(diào)用children的changeMsg方法
}
}
}
</script>
<style lang="sass" scoped></style>
總結(jié)
到此這篇關(guān)于Vue中ref和$refs的介紹以及使用的文章就介紹到這了,更多相關(guān)Vue中ref和$refs使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VUE 無限層級樹形數(shù)據(jù)結(jié)構(gòu)顯示的實(shí)現(xiàn)
在做項(xiàng)目中,會(huì)遇到一些樹形的數(shù)據(jù)結(jié)構(gòu),常用在左側(cè)菜單導(dǎo)航,本文就介紹一下如何實(shí)現(xiàn),感興趣的可以了解一下2021-07-07
vue.js打包項(xiàng)目后頁面出現(xiàn)空白的解決辦法
這篇文章主要介紹了vue.js打包項(xiàng)目后頁面出現(xiàn)空白的解決辦法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2021-11-11
vue在響應(yīng)頭response中獲取自定義headers操作
這篇文章主要介紹了vue在響應(yīng)頭response中獲取自定義headers操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
vue實(shí)現(xiàn)三級導(dǎo)航展示和隱藏
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)三級導(dǎo)航展示和隱藏,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
vue3+ts中ref與reactive指定類型實(shí)現(xiàn)示例
這篇文章主要為大家介紹了vue3+ts中ref及reactive如何指定類型的實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06

