浅谈 ref 引用
1. 什么是 ref 引用
ref 用来辅助开发者在不依赖于 jQuery 的情况下,获取 DOM 元素或组件的引用。
每个 vue 的组件实例上,都包含一个 $refs 对象,里面存储着对应的 DOM 元素或组件的引用。默认情况下,
组件的 $refs 指向一个空对象。
<template>
<div class="app-container">
<h1 ref="myref">MyRef 组件</h1>
<button @click="MyrefFn">获取 $refs 引用</button>
</div>
</template>
<script>
export default {
methods: {
MyrefFn() {
console.log(this) // this 为当前组件的实例对象
}
}
}
</script>
复制代码
控制台打印
2. 使用 ref 引用 DOM 元素
如果想要使用 ref 引用页面上的 DOM 元素,则可以按照如下的方式进行操作:
<template>
<div class="app-container">
<h1 ref="myref">MyRef 组件</h1>
<button @click="MyrefFn">获取 $refs 引用</button>
</div>
</template>
<script>
export default {
methods: {
MyrefFn() {
console.log(this.$refs.myref)
this.$refs.myref.style.color = 'red'
}
}
}
</script>
复制代码
控制台打印
3. 使用 ref 引用组件实例
如果想要使用 ref 引用页面上的组件实例,则可以按照如下的方式进行操作:
<template>
<div class="app-container">
<h1>MyRef 组件</h1>
<Mycomponent ref="myref"></Mycomponent>
<button @click="MyrefFn">获取 $refs 引用</button>
</div>
</template>
<script>
// 引入组件
import Mycomponent from '@/components/Mycomponent.vue'
export default {
// 注册组件
components: {
Mycomponent
},
methods: {
MyrefFn() {
console.log(this.$refs.myref) // ref 使用在组件身上拿到的就是组件实例
}
}
}
</script>
复制代码
控制台打印
4. 控制文本框和按钮的按需切换,并自动聚焦
通过布尔值 show 来控制组件中的文本框与按钮的按需切换。示例代码如下:
<template>
<div class="app-container">
<input ref="inp" type="text" v-if="show" @blur="show = false" />
<button v-else @click="showFn">切换 input</button>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
},
methods: {
showFn() {
this.show = true
// 让输入框自动聚焦
this.$refs.inp.focus()
}
}
}
</script>
复制代码
点击切换的时候,每次切换到输入框都要手动聚焦,然后才能触发 blur 事件,所以加一句让 input 自动聚焦的代码
运行上面代码就会发现其实输入框并没有自动聚焦,原因是在切换的时候 input 框处于在生命周期的 created 函数,而这个阶段 DOM 元素还没有被创建,拿不到 DOM 元素,因此没有达到预期的效果,接下来就介绍一下组建的 $nextTick() 方法
运行
5. this.$nextTick(callback) 方法
组件的 $nextTick(callback) 方法,会把 callback回调推迟到下一个 DOM 更新周期之后执行。通俗的理解是:等组件的 DOM 更新完成之后,再执行 callback回调函数。从而能保证 callback回调函数可以操作到最新的 DOM 元素
把上面的代码拿下来
<template>
<div class="app-container">
<input ref="inp" type="text" v-if="show" @blur="show = false" />
<button v-else @click="showFn">切换 input</button>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
},
methods: {
showFn() {
this.show = true
// 让输入框自动聚焦
this.$nextTick(() => {
this.$refs.inp.focus()
})
}
}
}
</script>
复制代码
运行
总结:ref 用来辅助开发者在不依赖于 jQuery 的情况下,获取 DOM 元素或组件的引用。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END