SoFunction
Updated on 2025-04-04

Four ways to operate dom in Vue3, nanny-level tutorial (recommended!)

Preface

Recently, the supervisor has put forward many requirements for optimizing the user experience, many of which involvedomoperate. This article will include common ones in Vue3domA summary of the operation. I think the article is good or it may be helpful for my own development!

1. Get the quotation of dom through ref

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

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

BydivElement additionrefAttribute, in order to obtain this element, we declare arefvariable with the same attribute name, then pass[Variable name].valueThis can be obtained in the form ofdivelement.

Applicable scenarios

  • singledomA scene with fewer elements or fewer numbers

Sample code

&lt;template&gt;
    &lt;div class="ref-container"&gt;
        &lt;p&gt;pass ref Get it directly dom&lt;/p&gt;
        &lt;div ref="sectionRef" class="ref-section"&gt;&lt;/div&gt;
        &lt;button @click="action" class="btn"&gt;Get high&lt;/button&gt;
    &lt;/div&gt;
&lt;/template&gt;

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

const action= () =&gt; {
    height += 50;
     = `height: ${height}px`;
}
&lt;/script&gt;

&lt;style lang="scss" scoped&gt;
.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;
    }
}
&lt;/style&gt;

2. Get the dom reference through the ref traversal of the parent container

By adding to the parent elementrefand declare a property withrefVariables with the same attribute namelist, at this timeWill get a child elementdomObject. It can be passed[index]Get child elements in the formdom

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

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

Applicable scenarios

  • passv-forA scene with a fixed number of elements generated by loops.

Sample code

&lt;template&gt;
    &lt;div class="ref-container"&gt;
        &lt;p&gt;Get it through parent container traversaldom&lt;/p&gt;
        &lt;div ref="list" class="list-section"&gt;
            &lt;div @click="higherAction(index)" class="list-item" v-for="(item, index) in " :key="index"&gt;
                &lt;span&gt;{{item}}&lt;/span&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/template&gt;

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

const higherAction = (index: number) =&gt; {
    let height = [index]. ? [index]. : '20px';
    height = Number(('px', ''));
    [index].style = `height: ${height + 20}px`;
}
&lt;/script&gt;

&lt;style lang="scss" scoped&gt;
.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;
        }
    }
}
&lt;/style&gt;

3. Pass ref through subcomponent emit

Adding to subcomponentsrefand declare a property withrefVariables with the same attribute namechildRef, at this timeemitWillAs adomPass the reference out.

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

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

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

Applicable scenarios

  • Multiple pages may have operation componentsdomScene of

Sample code

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

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

const props = defineProps({
    item: Number
})
const emit = defineEmits(['cellTap']);
const childRef = ref()
const cellAction = () => {
    emit('cellTap', );
}
</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>
&lt;template&gt;
    &lt;div class="ref-container"&gt;
        &lt;p&gt;Through subcomponentsemittransferref&lt;/p&gt;
        &lt;div class="list-section"&gt;
            &lt;Cell :item="item" @cellTap="cellTapHandler" v-for="(item, index) in " :key="index"&gt;
            &lt;/Cell&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/template&gt;

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

const cellTapHandler = (el: any) =&gt; {
    let height =  ?  : '20px';
    height = Number(('px', ''));
     = `height: ${height + 20}px`;
}
&lt;/script&gt;

&lt;style lang="scss" scoped&gt;
.demo2-container {
    width: 100%;
    height: 100%;

    .list-section {
        width: 200px;
    }
}
&lt;/style&gt;

4. Put the dom reference into the array through :ref

pass:refLoop callsetRefActionMethod, this method will receive aelParameter, this parameter is what we need to obtaindivelement.

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

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

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

const setRefAction = (el: any) => {
    (el);
}
</script>

It can be passed[index]Get child elements in the formdom

Applicable scenarios

  • passv-forA scene with an unfixed number or multiple elements generated by a loop.

Sample code

&lt;template&gt;
    &lt;div class="ref-container"&gt;
        &lt;p&gt;pass:refWilldomPut references into array&lt;/p&gt;
        &lt;div class="list-section"&gt;
            &lt;div :ref="setRefAction" @click="higherAction(index)" class="list-item" v-for="(item, index) in " :key="index"&gt;
                &lt;span&gt;{{item}}&lt;/span&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;script lang="ts" setup&gt;
import { reactive } from 'vue'

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

const higherAction = (index: number) =&gt; {
    let height = [index]. ? [index]. : '20px';
    height = Number(('px', ''));
    [index].style = `height: ${height + 20}px`;
    ([index]);
}

const setRefAction = (el: any) =&gt; {
    (el);
}
&lt;/script&gt;

&lt;style lang="scss" scoped&gt;
.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;
        }
    }
}
&lt;/style&gt;

Attachment: Get dom in vue3, there are a few points to pay attention to

1. Get the name of the ref element of the dom, and correspond to the exposed name, otherwise an invalid dom error will occur, that is, the one you get is null

2. In setup, use ref (null) to get the dom

3. You cannot get the dom value directly in the setup, because the corresponding life cycle of the setup is created, so it must be obtained in the subsequent life cycle hook, such as onMounted

Summarize

After continuous exploration, it was finally completed. After thinking about it, my ability was not enough, and I still need to continuously improve my abilities in the future ~ ~ ~

This is the end of this article about the four ways to operate dom in Vue3. For more related content on Vue3 operating dom, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!