更新時(shí)間:2021-12-30 來(lái)源:黑馬程序員 瀏覽量:
ref 用來(lái)輔助開(kāi)發(fā)者在不依賴(lài)于 jQuery 的情況下,獲取 DOM 元素或組件的引用。
每個(gè) vue 的組件實(shí)例上,都包含一個(gè) $refs 對(duì)象,里面存儲(chǔ)著對(duì)應(yīng)的 DOM 元素或組件的引用。默認(rèn)情況下,組件的 $refs
指向一個(gè)空對(duì)象。
< template >
< h3 > MyRef 組件 < /h3>
< button @click = "getRef" > 獲取$refs 引用 < /button>
< /template>
<script >
export default {
methods: {
getRef() {console.log(this)} // this代表當(dāng)前組件的實(shí)例對(duì)象,this.$refs默認(rèn)指向空對(duì)象
}
} < /script>如果想要使用 ref 引用頁(yè)面上的 DOM 元素,則可以按照如下的方式進(jìn)行操作:
<!--使用ref屬性,為對(duì)應(yīng)的DOM添加引用名稱(chēng)-->
<h3 ref="myh3">MyRef組件</h3>
<button @click="getRef">獲取$refs 引用</button>
methods: {
getRef() {
//通過(guò) this.$refs.引用的名稱(chēng)可以獲取到 DOM元素的引用
console.log(this.$refs.myh3) //操作DOM元素,把文本顏色改為紅色
this.$refs.myh3.style.color='red'
},
}如果想要使用 ref 引用頁(yè)面上的組件實(shí)例,則可以按照如下的方式進(jìn)行操作:
<!--使用ref屬性,為對(duì)應(yīng)的“組件“添加引用名稱(chēng)-->
<my-counter ref="counterRef">
</my-counter>
<button @click="getRef">獲取$refs 引用</button>
methods: {
getRef() {
//通過(guò) this.$refs.引用的名稱(chēng) 可以引用組件的實(shí)例
console.log(this.$refs.counterRef)
//引用到組件的實(shí)例之后,就可以調(diào)用組件上的methods方法
this.$refs.counterRef.add()
},
}通過(guò)布爾值 inputVisible 來(lái)控制組件中的文本框與按鈕的按需切換。示例代碼如下:
<template> <input type="text" v-if="inputVisible" <button v-else @click="showInput">展示input輸入框</button> </template>
< script >
export default {
data() {
return {
//控制文本框和按鈕的按需切換
inputVisible: false,
}
},
methods: {
showInput() { //切換布爾值,顯示文本框
this.inputVisible = true
},
},
}
< /script>當(dāng)文本框展示出來(lái)之后,如果希望它立即獲得焦點(diǎn),則可以為其添加 ref 引用,并調(diào)用原生 DOM 對(duì)象的.focus() 方法即可。示例代碼如下:
< input type = "text" v -if = "inputVisible" ref = "ipt" >
< button v -else @click = "showInput" > 展示input輸入框 < /button>
metNods: {
showInput() {
this.inputVisible = true
//獲取文本框的DOM引用,并調(diào)用.focus()使其自動(dòng)獲得焦點(diǎn)
this.$refs.ipt.focus()
},
}組件的 $nextTick(cb) 方法,會(huì)把 cb 回調(diào)推遲到下一個(gè) DOM 更新周期之后執(zhí)行。通俗的理解是:等組件的DOM 異步地重新渲染完成后,再執(zhí)行 cb 回調(diào)函數(shù)。從而能保證 cb 回調(diào)函數(shù)可以操作到最新的 DOM 元素。
<input type="text"v-if="inputVisible" ref="ipt">
<button v-else @click="showInput">展示input輸入框</button>
methods: {
showInput() {
this.inputVisible = true
//把對(duì)input文本框的操作,推遲到下次DOM更新之后。否則頁(yè)面上根本不存在文本框元素
this.$nextTick(() => {
this.$refs.ipt.focus()
})
},
}IT就到黑馬程序員.gif)