Vue3中操作dom的四种方式总结(建议收藏!)

目录
  • 前言
  • 通过ref直接拿到dom引用
    • 适用场景
    • 示例代码
  • 通过父容器的ref遍历拿到dom引用
    • 适用场景
    • 示例代码
  • 通过:ref将dom引用放到数组中
    • 适用场景
    • 示例代码
  • 通过子组件emit传递ref
    • 适用场景
    • 示例代码
  • 写在最后

前言

最近产品经理提出了很多用户体验优化的需求,涉及到很多dom的操作。

小张:“老铁,本来开发Vue2项目操作dom挺简单的,现在开发vue3项目,突然感觉一头雾水!”

我:“没事,原理都差不多,查查资料应该没问题的!”

至此将Vue3中dom操作常见的几种方式总结一下!

通过ref直接拿到dom引用

<template>
    <div class="demo1-container">
        <div ref="sectionRef" class="ref-section"></div>
    </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
const sectionRef = ref()
</script>

通过对div元素添加了ref属性,为了获取到这个元素,我们声明了一个与ref属性名称相同的变量sectionRef,然后我们通过 sectionRef.value 的形式即可获取该div元素。

适用场景

单一dom元素或者个数较少的场景

示例代码

<template>
    <div class="demo1-container">
        <p>通过ref直接拿到dom</p>
        <div ref="sectionRef" class="ref-section"></div>
        <button @click="higherAction" class="btn">变高</button>
    </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
const sectionRef = ref()
let height = 100;

const higherAction = () => {
    height += 50;
    sectionRef.value.style = `height: ${height}px`;
}
</script>

<style lang="scss" scoped>
.demo1-container {
    width: 100%;
    height: 100%;

    .ref-section {
        width: 200px;
        height: 100px;
        background-color: pink;
        transition: all .5s ease-in-out;
    }

    .btn {
        width: 200px;
        height: 50px;
        background-color: gray;
        color: #fff;
        margin-top: 100px;
    }
}
</style>

通过父容器的ref遍历拿到dom引用

<template>
    <div class="demo2-container">
        <div ref="listRef" class="list-section">
            <div @click="higherAction(index)" class="list-item" v-for="(item, index) in state.list" :key="index">
                <span>{{item}}</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
const listRef = ref()

通过对父元素添加了ref属性,并声明了一个与ref属性名称相同的变量listRef,此时通过listRef.value会获得包含子元素的dom对象

此时可以通过listRef.value.children[index]的形式获取子元素dom

适用场景

通过v-for循环生成的固定数量元素的场景

示例代码

<template>
    <div class="demo2-container">
        <p>通过父容器遍历拿到dom</p>
        <div ref="listRef" class="list-section">
            <div @click="higherAction(index)" class="list-item" v-for="(item, index) in state.list" :key="index">
                <span>{{item}}</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
const listRef = ref()
const state = reactive({
    list: [1, 2, 3, 4, 5, 6, 7, 8]
})

const higherAction = (index: number) => {
    let height = listRef.value.children[index].style.height ? listRef.value.children[index].style.height : '20px';
    height = Number(height.replace('px', ''));
    listRef.value.children[index].style = `height: ${height + 20}px`;
}
</script>

<style lang="scss" scoped>
.demo2-container {
    width: 100%;
    height: 100%;

    .list-section {
        width: 200px;
        .list-item {
            width: 200px;
            height: 20px;
            background-color: pink;
            color: #333;
            transition: all .5s ease-in-out;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}
</style>

通过:ref将dom引用放到数组中

<template>
    <div class="demo2-container">
        <div class="list-section">
            <div :ref="setRefAction" @click="higherAction(index)" class="list-item" v-for="(item, index) in state.list" :key="index">
                <span>{{item}}</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'

const state = reactive({
    list: [1, 2, 3, 4, 5, 6, 7],
    refList: [] as Array<any>
})

const setRefAction = (el: any) => {
    state.refList.push(el);
}
</script>

通过:ref循环调用setRefAction方法,该方法会默认接收一个el参数,这个参数就是我们需要获取的div元素

此时可以通过state.refList[index]的形式获取子元素dom

适用场景

通过v-for循环生成的不固定数量或者多种元素的场景

示例代码

<template>
    <div class="demo2-container">
        <p>通过:ref将dom引用放到数组中</p>
        <div class="list-section">
            <div :ref="setRefAction" @click="higherAction(index)" class="list-item" v-for="(item, index) in state.list" :key="index">
                <span>{{item}}</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'

const state = reactive({
    list: [1, 2, 3, 4, 5, 6, 7],
    refList: [] as Array<any>
})

const higherAction = (index: number) => {
    let height = state.refList[index].style.height ? state.refList[index].style.height : '20px';
    height = Number(height.replace('px', ''));
    state.refList[index].style = `height: ${height + 20}px`;
    console.log(state.refList[index]);
}

const setRefAction = (el: any) => {
    state.refList.push(el);
}
</script>

<style lang="scss" scoped>
.demo2-container {
    width: 100%;
    height: 100%;

    .list-section {
        width: 200px;
        .list-item {
            width: 200px;
            height: 20px;
            background-color: pink;
            color: #333;
            transition: all .5s ease-in-out;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}
</style>

通过子组件emit传递ref

<template>
    <div ref="cellRef" @click="cellAction" class="cell-item">
        <span>{{item}}</span>
    </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';

const props = defineProps({
    item: Number
})
const emit = defineEmits(['cellTap']);
const cellRef = ref();
const cellAction = () => {
    emit('cellTap', cellRef.value);
}
</script>

通过对子组件添加了ref属性,并声明了一个与ref属性名称相同的变量cellRef,此时可以通过emit将cellRef.value作为一个dom引用传递出去

适用场景

多个页面都可能有操作组件dom的场景

示例代码

<template>
    <div ref="cellRef" @click="cellAction" class="cell-item">
        <span>{{item}}</span>
    </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';

const props = defineProps({
    item: Number
})
const emit = defineEmits(['cellTap']);
const cellRef = ref();
const cellAction = () => {
    emit('cellTap', cellRef.value);
}
</script>

<style lang="scss" scoped>
.cell-item {
    width: 200px;
    height: 20px;
    background-color: pink;
    color: #333;
    transition: all .5s ease-in-out;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
<template>
    <div class="demo2-container">
        <p>通过子组件emit传递ref</p>
        <div class="list-section">
            <Cell :item="item" @cellTap="cellTapHandler" v-for="(item, index) in state.list" :key="index">
            </Cell>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import Cell from '@/components/Cell.vue'
const state = reactive({
    list: [1, 2, 3, 4, 5, 6, 7],
    refList: [] as Array<any>
})

const cellTapHandler = (el: any) => {
    let height = el.style.height ? el.style.height : '20px';
    height = Number(height.replace('px', ''));
    el.style = `height: ${height + 20}px`;
}
</script>

<style lang="scss" scoped>
.demo2-container {
    width: 100%;
    height: 100%;

    .list-section {
        width: 200px;
    }
}
</style>

写在最后

到此这篇关于Vue3中操作dom的四种方式总结的文章就介绍到这了,更多相关Vue3操作dom方式内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Vue3通过ref操作Dom元素及hooks的使用方法

    Vue3 ref获取DOM元素 <div ref="divBox">Hello</div> import {ref,onMounted} from 'vue' setup() { const divBox = ref(null); onMounted(()=>{ console.log(divBox.value); }) return{divBox} } 父组件监听子组件中的元素 在父组件中的子组件里会打印一个proxy(实例),通过实例去获取里面的属性或

  • vue3中的hooks总结

    目录 vue3的hooks总结 计数器的hook vue3自定义hooks vue3的hooks总结 vue3中的hooks其实是函数的写法,就是将文件的一些单独功能的js代码进行抽离出来,放到单独的js文件中.这样其实和我们在vue2中学的mixin比较像.下面我们总结一下如何去书写hooks. 首先应该先建立一个hooks文件夹:其目的是为了存放hook文件. 建立相关的hook文件:一般使用use开头. 计数器的hook useTitle的hooks useScrollPostion用来监

  • vue3自定义hooks/可组合函数方式

    目录 自定义hooks/可组合函数 1.mixins方式的痛点 2.传统mixins方式示例 3.自定义hooks方式示例 vue3(hooks) 自定义hooks/可组合函数 vue3 composition api下mixins的替代方式(自定义hooks / 可组合函数) 传统方式下封装的mixins在引入文件里都是通过this来调用属性或方法, 而在vue3的composition API下this是undefined,实际上这两者就是冲突的, 只能封装一套全新的方式来使用类似mixin

  • Vue3使用hooks函数实现代码复用详解

    目录 前言 VUE2我们是怎么做的呢? VUE3中我们怎么处理复用代码逻辑的封装呢? 说那么多,不如直接上代码来看差异 前言 项目开发过程中,我们会遇到一些情况,就是多个组件都可以重复使用的一部分代码逻辑,功能函数,我们想要复用,这可怎么办呢? VUE2我们是怎么做的呢? 在vue2 中有一个东西:Mixins 可以实现这个功能 mixins就是将这些多个相同的逻辑抽离出来,各个组件只需要引入mixins,就能实现代码复用 弊端一: 会涉及到覆盖的问题 组件的data.methods.filte

  • vue3使用自定义hooks获取dom元素的问题说明

    目录 使用自定义hooks获取dom元素问题 分享下楼主自己的观点 vue获取/操作组件的dom元素 下面是我的代码内容(非全部内容) 最后总结 使用自定义hooks获取dom元素问题 在自定义hooks的onMounted事件里面 获取ref元素,组件调用hooks的时候必须要传递响应式对象. 分享下楼主自己的观点 代码如下 <script> // demo.vue import { defineComponent, ref } from 'vue' import useBars from

  • vue3在自定义hooks中使用useRouter报错的解决方案

    目录 自定义hooks中使用useRouter报错 useRouter useRoute 使用Vue.use()报错“Cannot read property ‘use‘ of undefined” 原因 正解 自定义hooks中使用useRouter报错 随着vue3的更新,vue-router也更新到了4.x useRouter 相当于vue2的this.$router全局的路由实例,是router构造方法的实例 useRoute 相当于vue2的this.$route表示当前激活的路由的状

  • vue3的setup语法如何自定义v-model为公用hooks

    目录 前言 基础 基本的v-model 多个v-model绑定 v-model修饰符 进阶 问题背景 方式一:通过watch中转 方式二:computed的get和set 终极:封装v-model的hooks 提取公用逻辑 继续抽离封装 前言 基础篇:简单介绍vue3的setup语法如何自定义v-model: 进阶篇:如何提取v-model语法作为一个公用hooks: 基础 基础篇可绕过,只是对于官网给出的教程,进行了总结概括并给出demo 基本的v-model 子组件中满足两个点,即可完成自定

  • Vue3项目中的hooks的使用教程

    目录 hooks 特点 hooks 基本使用 今天我们稍微说一下 vue3 项目中的 hooks 的使用,其实这个 hooks 呢是和 vue2 当中的 mixin 是类似的,学习过 vue2 的小伙伴一定对 mixin 一定比较熟悉,就算没用过也一定了解过,也就是混入,通过 mixin 混入来分发 vue 组件中的可复用功能.一个混入对象可以包含任意组件选项.当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项.而 vue2 的 hooks 函数与 mixin 混入的区别,

  • Vue3中操作dom的四种方式总结(建议收藏!)

    目录 前言 通过ref直接拿到dom引用 适用场景 示例代码 通过父容器的ref遍历拿到dom引用 适用场景 示例代码 通过:ref将dom引用放到数组中 适用场景 示例代码 通过子组件emit传递ref 适用场景 示例代码 写在最后 前言 最近产品经理提出了很多用户体验优化的需求,涉及到很多dom的操作. 小张:“老铁,本来开发Vue2项目操作dom挺简单的,现在开发vue3项目,突然感觉一头雾水!” 我:“没事,原理都差不多,查查资料应该没问题的!” 至此将Vue3中dom操作常见的几种方式

  • Java中遍历ConcurrentHashMap的四种方式详解

    这篇文章主要介绍了Java中遍历ConcurrentHashMap的四种方式详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 方式一:在for-each循环中使用entries来遍历 System.out.println("方式一:在for-each循环中使用entries来遍历");for (Map.Entry<String, String> entry: map.entrySet()) { System.out.pr

  • Pandas中根据条件替换列中的值的四种方式

    目录 方法1:使用dataframe.loc[]函数 方法2:使用NumPy.where()函数 方法3:使用pandas掩码函数 方法4:替换包含指定字符的字符串 方法1:使用dataframe.loc[]函数 通过这个方法,我们可以用一个条件或一个布尔数组来访问一组行或列.如果我们可以访问它,我们也可以操作它的值,是的!这是我们的第一个方法,通过pandas中的dataframe.loc[]函数,我们可以访问一个列并通过一个条件改变它的值. 语法:df.loc[ df["column_nam

  • Spring中集成Groovy的四种方式(小结)

    groovy是一种动态脚本语言,适用于一些可变.和规则配置性的需求,目前Spring提供ScriptSource接口,支持两种类型,一种是 ResourceScriptSource,另一种是 StaticScriptSource,但是有的场景我们需要把groovy代码放进DB中,所以我们需要扩展这个. ResourceScriptSource:在 resources 下面写groovy类 StaticScriptSource:把groovy类代码放进XML里 DatabaseScriptSour

  • Python中引用传参四种方式介绍

    目录 引用传参一: ​引用传参二: ​​引用传参三: ​​引用传参四: 总结 引用传参一: ​​>>> a = 100 #这里的a是不可变类型 >>> def test(a): ... a+=a #这个式子有两层含义:1.这里可能是重新定义一个新的变量a,2.也有可能是修改a的值,但由于全局 #变量a不能修改,所以此处是重新定义了一个a: ... print("函数内:%d"%a) ... >>> test(a) 函数内:200 &

  • Python函数中定义参数的四种方式

    Python中函数参数的定义主要有四种方式: 1. F(arg1,arg2,-) 这是最常见的定义方式,一个函数可以定义任意个参数,每个参数间用逗号分割,用这种方式定义的函数在调用的的时候也必须在函数名后的小括号里提供个数相等 的值(实际参数),而且顺序必须相同,也就是说在这种调用方式中,形参和实参的个数必须一致,而且必须一一对应,也就是说第一个形参对应这第一个实参.例如: 复制代码 代码如下: def a(x,y):print x,y 调用该函数,a(1,2)则x取1,y取2,形参与实参相对应

  • Spring中实例化bean的四种方式详解

    前言 在介绍Bean的实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果把Spring看作一个大型工厂,那么Spring容器中的Bean就是该工厂的产品.要想使用Spring工厂生产和管理Bean,就需要在配置文件中指明需要哪些Bean,以及需要使用何种方式将这些Bean装配到一起. Spring容器支持两种格式的配置文件,分别为Properties文件格式和xml文件格式,而在实际的开发当中,最常使用的额是xml文件格式,因此在如下的讲解中,我们以xml文件格

  • vue中组件通信的八种方式(值得收藏!)

    前言 之前写了一篇关于vue面试总结的文章, 有不少网友提出组件之间通信方式还有很多, 这篇文章便是专门总结组件之间通信的 vue是数据驱动视图更新的框架, 所以对于vue来说组件间的数据通信非常重要,那么组件之间如何进行数据通信的呢? 首先我们需要知道在vue中组件之间存在什么样的关系, 才更容易理解他们的通信方式, 就好像过年回家,坐着一屋子的陌生人,相互之间怎么称呼,这时就需要先知道自己和他们之间是什么样的关系. vue组件中关系说明: 如上图所示, A与B.A与C.B与D.C与E组件之间

  • Android 实现定时器的四种方式总结及实现实例

    Android中实现定时器的四种方式 第一种方式利用Timer和TimerTask 1.继承关系 java.util.Timer 基本方法 schedule 例如: timer.schedule(task, delay,period); //delay为long,period为long:从现在起过delay毫秒以后,每隔period毫秒执行一次. schedule方法有三个参数 第一个参数就是TimerTask类型的对象,我们实现TimerTask的run()方法就是要周期执行的一个任务: 第二

  • Java遍历Map四种方式讲解

    Java中遍历Map的四种方式 在java中所有的map都实现了Map接口,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历. 方法一:在for循环中使用entries实现Map的遍历: /** * 最常见也是大多数情况下用的最多的,一般在键值对都需要使用 */ Map <String,String>map = new HashMap<String,String>(); map.put("

随机推荐