时间:2023-01-20 09:33:57 | 栏目:vue | 点击:次
$refs是vue提供的获取真实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>
【控制台效果】:

【代码演示】:
<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等待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>
【效果演示】:

【代码演示】:
<template>
<div>
<p>vue异步更新dom</p>
<p ref="mycount">{{ count }}</p>
<button @click="add1">点击+1,马上获取数据</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
add1() {
this.count++;
// console.log(this.$refs.mycount.innerHTML);
// 解决异步更新问题
// dom更新完成之后会顺序执行this.$nextTick()中的函数体
this.$nextTick(() => {
console.log(this.$refs.mycount.innerHTML);
});
},
},
};
</script>
<style>
</style>
【效果演示】:

【代码演示】:
<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>
【效果】:

