$refs使用
作用:可以获取页面dom元素或者组件,
属性语法:
调用:ref="自定义属性名"
使用:this.$refs.调用里自定义的属性名
<template>
<div style="border:1px solid #ccc; margin:5px;padding:5px">
<h1>37-refs</h1>
<!-- 1. 添加一个ref属性 -->
<h2 ref="refH2">获取 dom元素 或者 组件</h2>
<button @click="fn">获取dom</button>
<MyCom ref="refMyCom"/>
<button @click="fn2">获取子组件</button>
</div>
</template>
<script>
// 导入->注册->使用
import MyCom from './components/MyCom.vue'
export default {
components: { MyCom },
methods: {
fn(){
// 1. 获取dom原生的方式
// document.querySelector('h2')
// 2. 获取dom原生的方式2 this.$refs.ref的值
// console.log(this.$refs.refH2.innerHTML)
},
fn2(){
console.log(this.$refs.refMyCom.num); //控制台会打印,MyCom子组件里的元素内容
}
}
}
</script>
nextTick使用
vue 数据驱动视图,数据改变会导致视图(页面上的dom)更新,这个过程是异步的!dom并没有同步更新,视图更新后并不会立即执行而是会把数据放在一个队列或者数组里面,只有当同步代码执行完毕后才会更新视图
用法: this.$nextTeck(() => { 事件处理 })
nextTick作用:可以使同步的代码执行完毕后立马执行他,
<template>
<div>
<input ref="refInput" v-if="isShow">
<!-- ref属性名是固定的 -->
<button v-else @click="fn">搜索</button>
</div>
</template>
<script>
export default {
data() {
return {
isShow:false
}
},
methods: {
fn(){
// 1.更新isShow
this.isShow=true //修改状态视图要更新
//视图更新是异步的,变量改了之后,视图不会立即马上更新,变量改了之后,把 更新视图() 等一段时间后在执行
this.$nextTick(()=>{ //使用nextTick视图更新完毕后,会立即执行下面代码,不然不会执行下面的代码
// 2.找到input,调用focus
this.$refs.refInput.focus()
})
}
},
}
</script>