詳解Vue中$refs和$nextTick的使用方法
1、$refs簡介
$refs是vue提供的獲取真實dom的方法。
$refs獲取DOM元素
【使用步驟】:
在原生DOM元素上添加ref屬性利用this.$refs獲取原生的DOM元素
【代碼演示】:
<template>
<div>
<h1>獲取原生的DOM元素</h1>
<h4 id="h" ref="myH">我是h4標簽</h4>
</div>
</template>
<script>
export default {
// 在掛載之后獲取原生dom
mounted() {
console.log(document.getElementById("h"));
// this.$refs是vue對象中特有的屬性
console.log(this.$refs.myH);
},
};
</script>
<style>
</style>
【控制臺效果】:

$refs獲取組件對象
【代碼演示】:
<template>
<div>
<h1>獲取組件對象</h1>
<Demo ref="myCom"></Demo>
</div>
</template>
<script>
import Demo from "@/components/Demo";
export default {
mounted() {
console.log(this.$refs.myCom);
// 獲取子組件對象
let demo = this.$refs.myCom;
// 調(diào)用子組件中的方法
demo.fn();
},
components: {
Demo,
},
};
</script>
<style>
</style>
【效果展示】:

2、$nextTick基本使用
$nextTick等待dom更新之后執(zhí)行方法中的函數(shù)體
vue異步更新DOM
【vue異步更新演示】:
<template>
<div>
<h1>獲取組件對象</h1>
<Demo ref="myCom"></Demo>
</div>
</template>
<script>
import Demo from "@/components/Demo";
export default {
mounted() {
console.log(this.$refs.myCom);
// 獲取子組件對象
let demo = this.$refs.myCom;
// 調(diào)用子組件中的方法
demo.fn();
},
components: {
Demo,
},
};
</script>
<style>
</style>
【效果演示】:

利用$nextTick解決以上問題
【代碼演示】:
<template>
<div>
<p>vue異步更新dom</p>
<p ref="mycount">{{ count }}</p>
<button @click="add1">點擊+1,馬上獲取數(shù)據(jù)</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
add1() {
this.count++;
// console.log(this.$refs.mycount.innerHTML);
// 解決異步更新問題
// dom更新完成之后會順序執(zhí)行this.$nextTick()中的函數(shù)體
this.$nextTick(() => {
console.log(this.$refs.mycount.innerHTML);
});
},
},
};
</script>
<style>
</style>
【效果演示】:

$nextTick使用場景
【代碼演示】:
<template>
<div>
<p>$nextTick()使用場景</p>
<input
ref="search"
v-if="isShow"
type="text"
placeholder="這是一個輸入框"
/>
<button @click="search">點擊-立即搜索</button>
</div>
</template>
<script>
export default {
data() {
return {
isShow: false,
};
},
methods: {
search() {
this.isShow = true;
this.$nextTick(() => {
this.$refs.search.focus();
});
},
},
};
</script>
<style>
</style>
【效果】:


到此這篇關(guān)于詳解Vue中$refs和$nextTick的使用方法的文章就介紹到這了,更多相關(guān)Vue $refs $nextTick內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue-cli項目開發(fā)/生產(chǎn)環(huán)境代理實現(xiàn)跨域請求
這篇文章主要介紹了詳解vue-cli項目開發(fā)/生產(chǎn)環(huán)境代理實現(xiàn)跨域請求,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Vue3中Vuex狀態(tài)管理學(xué)習(xí)實戰(zhàn)示例詳解
這篇文章主要為大家介紹了Vue3中Vuex狀態(tài)管理學(xué)習(xí)實戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

