1. ref 引用
ref 用来辅助开发者在不依赖 jQuery 的情况下,获取DOM元素或组件的引用。
(1)每个vue的组件实例上,都包含一个$refs对象,里面存储着对应的DOM元素或组件的引用。默认情况下,组件的$refs指向一个空对象。
(2)使用ref引用页面上的DOM元素和引用页面上的组件实例:
<template>
<div>
<!-- 1、使用ref属性,为对应的DOM添加引用名称 -->
<h1 ref="myh11">App 根组件</h1>
<button type="button" class="btn btn-primary" @click="getRefs">获取 $refs 引用</button>
<!-- 3、使用ref属性,为组件添加引用名称 -->
<my-counter ref="counterRef"></my-counter>
</div>
</template>
<script>
// 导入组件
import MyCounter from './Counter.vue'
export default {
name: 'MyApp',
methods: {
getRefs() {
// this代表当前组件的实例对象,this.$refs默认指向空对象
// 通过this.$refs.引用的名称 可以获取到DOM元素的引用
// console.log(this.$refs)
// 2、操作DOM元素,把文本颜色变成红色
// this.$refs.myh11.style.color = 'red'
// 4、拿到组件的引用,调用组件上的reset()方法
// console.log(this.$refs.counterRef)
this.$refs.counterRef.reset()
},
},
// 注册组件
components: {
MyCounter,
},
}
</script>
<template>
<div class="counter-container">
<h3>Counter 组件 --- {
{ count }}</h3>
<hr />
<button type="button" class="btn btn-info" @click="count += 1">+1</button>
</div>
</template>
<script>
export default {
name: 'MyCounter',
data() {
return {
count: 0,
}
},
methods: {
reset() {
this.count = 0
},
},
}
</script>
<style lang="less" scoped>
.counter-container {
margin: 20px;
padding: 20px;
border: 1px solid #efefef;
border-radius: 4px;
box-shadow: 0px 1px 10px #efefef;
}
</style>
(3)控制文本框和按钮的按需切换
- 通过布尔值 inputVisible 来控制组件中文本框与按钮的按需切换。
- 当文本框展示出来之后,如果希望它立即获得焦点,可以为其添加 ref 引用,并调用原生 DOM 对象的 .focus() 方法即可。
- 在vue中DOM元素的更新是异步进行更新的,同步执行 this.$refs.ipt.focus() 时DOM还没有完成更新,此时还没有文本框,所以拿不到最新的DOM,会报错。需要将 this.$refs.ipt.focus() 这行代码进行延迟,延迟到DOM更新完成再执行,此时使用 this.$nextTick(cb)。
组件的 $nextTick(cb) 方法:把cb回调推迟到下一个DOM更新周期之后执行。(即,等组件的DOM异步地重新渲染完成后,再执行cb回调函数,从而保证cb回调函数可以操作到最新的DOM元素。)
<template>
<div>
<h1>App 根组件</h1>
<hr />
<input type="text" class="form-control" v-if="inputVisible" ref="ipt" />
<button type="button" class="btn btn-primary" v-else @click="showInput">展示 input 输入框</button>
</div>
</template>
<script