ref引用
ref
-
在vue中,不需要操作dom,只需要维护数据。
-
ref在不需要依赖jquery的情况下,获取dom元素或组件的引用。
-
每个vue的组件实例上,都包含一个 $refs 对象,里面存储着对应dom元素或组件的引用。
-
默认情况下,组件的$refs指向一个空对象。
-
ref可以父传子,也可以子传父。
-
在命名时最好将ref作为后缀。
-
在
console info(VueComponent)
中$
开头的都是vue内置的成员。
<h1 ref="myh1">App 根组件</h1> //console: $refs: myh1:h1 //myh1指向元素h1 //this.$refs.myh1 即指向元素h1 [[Prototype]]:Object
示例
<template> <!-- 引用 DOM 元素 --> <p ref="pp">这是段落</p> <button @click="getRef">获取 DOM 元素</button> <!-- 引用子组件 --> <son ref="sonRef"></son>//注意引用子组件是在父组件的子组件标签上使用ref。 <button @click="getComponent">获取子组件实例引用</button> </template> <script> methods: { getRef() { // 获取元素的引用 console.log(this.$refs.pp) this.$refs.pp.style.color = 'red' }, getComponent() { console.log(this.$refs.sonRef) // 可以访问子组件的数据和方法 this.$refs.sonRef.count = 1 this.$refs.sonRef.add() } } </script>
this.$nextTick(cb)
含义
this.$nextTick(cb)
是 Vue 实例的一个方法,用于在 DOM更新渲染完成后 执行回调函数 cb
。在 Vue 中,数据的变化可能会导致 DOM 的更新,但是 DOM 的更新并不是实时的,而是异步的,所以有时候需要在 DOM 更新后执行一些操作,比如访问更新后的 DOM 元素或执行其他操作。
this.$nextTick(cb)
的作用是将回调函数 cb
推入到 Vue 的更新队列中,等到 DOM 更新完成后再执行。这样可以确保在回调函数中访问到最新的 DOM 元素。
常见的用法场景包括:
-
在更新数据后立即访问更新后的 DOM 元素。
-
在 Vue 的生命周期钩子函数中进行 DOM 操作,确保操作发生在 DOM 更新后。
-
在异步操作中,等待 DOM 更新完成后再执行后续操作。
需要注意的是,this.$nextTick(cb)
是异步的,回调函数 cb
的执行顺序是在当前 JavaScript 执行完成后、DOM 更新前。
语法
this.$nextTick(() => { // 在 DOM 更新后执行回调函数 // 可以访问更新后的 DOM 元素 // 执行其他操作 });
示例
<template> ... <input type="text" v-if="inputVisible" ref="showInput" @blur="loseBlur"> <button v-else @click="changeInput">show input</button> ... </template> <script> export default { data() { return { inputVisible: false }, methods: { //点击按钮,展示输入框。 changeInput() { this.inputVisible = true //console.info(this.$refs.showInput) //this.$refs.showInput.focus() //展示输入框时展示焦点 this.$nextTick(() => { console.info(this.$refs.showInput); this.$refs.showInput.focus(); }); }, //失去焦点,隐藏输入框 loseBlur() { this.inputVisible = false }, }, }, </script>
TypeError
TypeError: Cannot read properties of undefined (reading 'focus')
当遇到类似的错误,表达的意思即为‘focus’之前的那个为undefined,在这里即为showInput
。
提示
将this.$refs.showInput.focus()
写在updated函数里可以实现效果但会报错:
因为updated是只要数据变化就会重新渲染,这会导致每一次数据变化都会使focus,然而很多时候只有按钮没有input。