詳解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;
// 調用子組件中的方法
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;
// 調用子組件中的方法
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>
【效果】:


到此這篇關于詳解Vue中$refs和$nextTick的使用方法的文章就介紹到這了,更多相關Vue $refs $nextTick內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue3 defineExpose要在方法聲明定義以后使用的教程
這篇文章主要介紹了Vue3 defineExpose要在方法聲明定義以后使用的教程,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
Vue2 Vue-cli中使用Typescript的配置詳解
Vue作為前端三大框架之一截至到目前在github上以收獲44,873顆星,足以說明其以悄然成為主流。下面這篇文章主要給大家介紹了關于Vue2 Vue-cli中使用Typescript的配置的相關資料,需要的朋友可以參考下。2017-07-07
Vue.js 中取得后臺原生HTML字符串 原樣顯示問題的解決方法
這篇文章主要介紹了VUE.js 中取得后臺原生HTML字符串 原樣顯示問題 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06
Javascript vue.js表格分頁,ajax異步加載數(shù)據(jù)
這篇文章主要介紹了Javascript vue.js表格分頁,ajax異步加載數(shù)據(jù)的相關資料,需要的朋友可以參考下2016-10-10
Vue中filter使用及根據(jù)id刪除數(shù)組元素方式
這篇文章主要介紹了Vue中filter使用及根據(jù)id刪除數(shù)組元素方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
Vue使用Tinymce富文本自定義toolbar按鈕的實踐
本文主要介紹了Vue使用Tinymce富文本自定義toolbar按鈕,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12

