天天看點

Vue3中操作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元素或者個數較少的場景

Vue3中操作ref的四種使用方式,建議收藏!

示例代碼

<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對象

Vue3中操作ref的四種使用方式,建議收藏!

此時可以通過listRef.value.children[index]的形式擷取子元素dom

适用場景

通過v-for循環生成的固定數量元素的場景

Vue3中操作ref的四種使用方式,建議收藏!

示例代碼

<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元素

Vue3中操作ref的四種使用方式,建議收藏!

此時可以通過state.refList[index]的形式擷取子元素dom

适用場景

通過v-for循環生成的不固定數量或者多種元素的場景

Vue3中操作ref的四種使用方式,建議收藏!

示例代碼

<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引用傳遞出去

Vue3中操作ref的四種使用方式,建議收藏!

适用場景

多個頁面都可能有操作元件dom的場景

Vue3中操作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>

<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>
複制代碼           

寫在最後

希望今天這篇文章對你有所幫助,小編隻是一個普普通通的程式員,如有不對的地方或者有探讨的地方,歡迎star~

繼續閱讀