vue3中通过ref获取元素节点(系列十一)
2023-09-11 14:20:08 时间
ref
过去在 Vue2
中,我们采用 ref
来获取标签的信息,用以替代传统 js 中的 DOM 行为。
<template> <div ref="box"> I am div </div> </template> console.log(this.$refs.box);
在 Vue3
的组合 API 中,采取了新的方案来执行对应的 ref
标签属性获取。过去我们采用的是 this.$refs
的方案,现在,要首先创建 ref
对象,然后再将这个 ref
对象创建出来,以实现监听。
<template> <div ref="box"> I am div </div> </template> <script> import { ref } from 'vue'; export default { name: 'App', setup() { let box = ref(null); return {box}; } } </script>
首先我们创建了一个 box
的监听对象,然后将这个监听对象暴露出去,从而实现 setup
函数中和 节点box
的绑定。
但由于 setup
函数的执行时间要先于 html
标签的渲染,所以我们不能直接在 setup
函数中初始化 box
标签。
beforeCreate
setup
Created
setup函数在这两个生命周期之间执行
setup() { let box = ref(null); // 此时的 box 虽然监听 div,但控制台打印的是 null。 console.log(box.value); return {box}; }
如果存在有初始化或类似的操作,需要借用 生命周期函数,而在 setup
中,要寻找生命周期需要用到 on+生命周期
的 api
。
选项 API | Hook inside inside setup |
---|---|
beforeCreate |
Not needed* |
created |
Not needed* |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeUnmount |
onBeforeUnmount |
unmounted |
onUnmounted |
errorCaptured |
onErrorCaptured |
renderTracked |
onRenderTracked |
renderTriggered |
onRenderTriggered |
通常来说,使用的会是 onMounted
.
<template> <div ref="box"> I am div </div> </template> <script> import { onMounted, ref } from 'vue'; export default { name: 'App', setup() { let box = ref(null); console.log(box.value); // 由于 template 中的 div 属性 ref 引用了一个对象 box,因此 box 将与这个 div 执行绑定。 // 但由于 setup 执行时期,还未创建实际的 div,所以如果要进行与 box 的交互,必须在生命周期中间执行获取。 // onMounted() 中的行为会在声明周期 mounted 中执行。 onMounted(() => { console.log('box.value', box.value); }) return {box}; } } </script>
至此,我们成功获取到了 box
指定的 div
标签。
相关文章
- vue3+Element-plus icon图标无法显示的问题(已解决)
- vue3学习笔记(Mixin混入)
- vue3组合式api 和 react自定义hooks
- 在 Vue3 成为默认版本后,盘点了 Vue3 与 Vue2 的区别
- Vue3+elementplus搭建通用管理系统实例十:动态表单及详情页实现上
- 浅析Vue3中如何通过v-model实现父子组件的双向数据绑定及利用computed简化父子组件双向绑定
- 浅析Vue3 CompositionAPI如何替换Vue Mixins:mixin的缺点(命名冲突、隐式依赖)、CompositionAPI如何解决这些缺陷(代码提取、代码重用)
- vue3中的双向绑定 proxy
- Vue3 为什么要用 Proxy 代替 Object.defineProperty 实现响应式
- 1.0 vue3数据变量的声明(ref & reactive)
- Vue3+Lodash:2023年了,我依然在使用Lodash