>  기사  >  웹 프론트엔드  >  Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법

Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법

青灯夜游
青灯夜游앞으로
2022-10-28 19:29:513446검색

Vue돔은 어떻게 운영하나요? 다음 글에서는 Vue3에서 DOM을 작동하는 네 가지 방법을 소개하겠습니다. 도움이 되셨으면 좋겠습니다!

Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법

최근 제품 관리자는 많은 DOM 작업을 포함하는 많은 사용자 경험 최적화 요구 사항을 제시했습니다.

Xiao Zhang: "Lao Tie, 예전에는 Vue2 프로젝트를 개발할 때 DOM을 조작하는 것이 꽤 간단했습니다. 이제 Vue3 프로젝트를 개발하고 있는데 갑자기 혼란스러워요!"

나: "괜찮아요. 원칙은 동일합니다. 정보를 확인하면 괜찮을 것입니다.”

Vue3의 몇 가지 일반적인 DOM 작업 방법을 요약합니다! (학습 영상 공유: vue 영상 튜토리얼)

ref

<template>
    <div>
        <div ref="sectionRef"></div>
    </div>
</template>

<script setup>
import {ref} from &#39;vue&#39;
const sectionRef = ref()
</script>
를 통해 직접 dom 참조 가져오기

div 요소에 ref 속성을 추가하여 이 요소를 가져오기 위해 동일한 dom 참조를 선언합니다. ref 속성 Variable sectionRef로 이름을 지정하면 sectionRef.value 형식으로 div 요소를 얻을 수 있습니다. Appplicable 시나리오

단일 dom 요소 또는 소수의 시나리오 교정 코드

<template>
    <div>
        <p>通过ref直接拿到dom</p>
        <div ref="sectionRef"></div>
        <button @click="higherAction">变高</button>
    </div>
</template>

<script setup>
import {ref} from &#39;vue&#39;
const sectionRef = ref()
let height = 100;

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

<style 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>

get get a peripling the parent container of the pert
<template>
    <div>
        <div ref="listRef">
            <div @click="higherAction(index)" v-for="(item, index) in state.list" :key="index">
                <span>{{item}}</span>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from &#39;vue&#39;
const listRef = ref()
e

Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법

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

<script setup>
import { ref, reactive } from &#39;vue&#39;
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 : &#39;20px&#39;;
    height = Number(height.replace(&#39;px&#39;, &#39;&#39;));
    listRef.value.children[index].style = `height: ${height + 20}px`;
}
</script>

<style 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>
a ad. parent 요소 ref 속성이 추가되고, ref 속성과 동일한 이름의 변수 listRef가 선언됩니다. 이때 자식 요소가 포함된 dom 객체는 listRef.value를 통해 가져옵니다. 하위 요소는 listRef.value.children[index]를 통해 얻을 수 있습니다. 하위 요소 dom을 가져옵니다

적용 가능한 시나리오

v-for 루프를 통해 생성된 고정된 수의 요소가 있는 시나리오

샘플 코드 Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법

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

<script setup>
import { reactive } from &#39;vue&#39;

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

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

<script setup>
import { reactive } from &#39;vue&#39;

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 : &#39;20px&#39;;
    height = Number(height.replace(&#39;px&#39;, &#39;&#39;));
    state.refList[index].style = `height: ${height + 20}px`;
    console.log(state.refList[index]);
}

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

<style 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>
를 통해 dom 참조를 배열에 넣습니다.
:ref 루프를 통해 setRefAction 메서드를 호출합니다. 이 메서드는 기본적으로 el 매개변수를 받습니다.

Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법이때, 하위 요소 dom은 state.refList[index]

형식으로 얻을 수 있습니다. 적용 가능한 시나리오

고정되지 않은 개수 또는 v-for 루프를 통해 여러 요소가 생성된 시나리오

예제 코드Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법

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

<script setup>
import {ref} from &#39;vue&#39;;

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

Pass ref through subcompontemitter

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

<script setup>
import {ref} from &#39;vue&#39;;

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

하위 컴포넌트에 추가 ref 속성이 선언되고, 이때 ref 속성과 동일한 이름의 cellRef 변수가 선언됩니다. .value는 Emit

Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법

적용 가능한 시나리오

여러 페이지에 작업이 있을 수 있음을 통해 DOM 참조로 전달될 수 있습니다. 우에스 입문 튜토리얼

,

웹 프론트엔드 시작하기]

위 내용은 Vue3는 DOM을 어떻게 운영하나요? 소개하는 네 가지 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 juejin.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제