什么是 ref 引用
- ref 用来辅助开发者在不依赖于 jQuery 的情况下,获取 DOM 元素或组件的引用。
- 每个 vue 的组件实例上,都包含一个 $refs 对象,里面存储着对应的 DOM 元素或组件的引用。默认情况下,组件的 $refs 指向一个空对象。
使用 ref 引用 DOM 元素
<h3 ref="myh3">MYRef 组件</h3>
<button @click="getRef">获取 $refs 引用</button>
methods: {
getRef(){
console.log(this.$refs.myh3);
// 操作DOM元素,把文本颜色渲染为 red
this.$refs.myh3.style.color = "red"
}
},
使用 ref 引用组件实例
<Left ref="LeftRef"></Left>
<button @click="getRef">获取 $refs 引用</button>
methods: {
getRef(){
console.log(this.$refs.LeftRef);
// 引用到组件之后就可以调用组件上的 methods 方法 (以 add() 为例)
this.$refs.LeftRef.add()
}
},
this.$nextTick(cb) 方法
组件的 $nextTick(cb) 方法,会把 cb 回调推迟到下一个 DOM 更新周期之后执行。通俗的理解是:等组件的
DOM 更新完成之后,再执行 cb 回调函数。从而能保证 cb 回调函数可以操作到最新的 DOM 元素。
以输入框和按钮之间的切换为例
- app.vue 组件
<template>
<div class="app-container">
<h1 ref="reference">App 根组件</h1>
<button @click="showthis">this</button>
------
<button @click="getcount">重置</button>
<hr />
<input type="text" v-if="visible" @blur="distinct" ref="iptref">
<button @click="action" v-else>转换</button>
<div class="box">
<!-- 渲染 Left 组件和 Right 组件 -->
<Left ref="oncom"></Left>
</div>
</div>
</template>
<script>
import Left from "./components/Left.vue"
export default {
components:{
Left
},
data() {
return {
visible : false
}
},
methods: {
showthis(){
this.$refs.reference.style.color = 'red'
},
getcount(){
this.$refs.oncom.resetcount()
},
action(){
this.visible = true
this.$nextTick(()=>{
this.$refs.iptref.focus()
})
},
distinct(){
this.visible = false
}
},
}
</script>
<style lang="less">
.app-container {
padding: 1px 20px 20px;
background-color: #efefef;
}
.box {
display: flex;
}
</style>
当文本框展示出来之后立即获得焦点,为其添加 ref 引用,并调用原生 DOM 对象的 .focus() 方法
- Left.vue 组件
<template>
<div class="left-container">
<h3>Left 组件</h3>
<p>count + 1 的结果为 : {{count}}</p>
<button @click="add">+1</button>
---------
<button @click="resetcount">重置</button>
</div>
</template>
<script>
export default {
data() {
return {
count : 0
}
},
methods: {
add(){
this.count += 1
},
resetcount(){
this.count = 0
}
},
}
</script>
<style lang="less">
.left-container {
padding: 0 20px 20px;
background-color: orange;
min-height: 250px;
flex: 1;
}
</style>