Vue操作DOM解決顯示位置問題
近來遇到的一個需求,簡單記錄一下思考和解決的過程
一、需求
上傳卡片按鈕,可顯示在上傳文件列表的首位,也可顯示在末尾。
簡化代碼如下:
// custom-upload 組件
<div class="wrapper" id="wrapper">
<el-upload />
<FilePreview
v-for="item in fileList"
:key="item.id"
:src="item.url" />
</div>
上傳卡片按鈕和上傳文件列表在一個div元素內(nèi),上傳卡片按鈕是div的第一個子元素,
需要擴展組件功能,上傳卡片按鈕可為div的最后一個元素
二、解決辦法及思路
一、增加prop參數(shù),用來控制上傳卡片的顯示位置,默認在首位
<script lang="ts" setup>
interface IProps {
position?: 'first' | 'last'
}
const props = withDefaults(defineProps<IProps>(), {
position: 'first',
})
</script>
二、控制上傳卡片按鈕的位置
(1)第一想法是,直接復制在一份在<FilePreview/ >后面,
通過參數(shù)控制顯示第一個還是最后一個,
此方法雖然方便快捷,但也有兩點缺點。
<div class="wrapper">
<el-upload v-if="props.position === 'first'" />
<FilePreview
v-for="item in fileList"
:key="item.id"
:src="item.url" />
<el-upload v-if="props.position === 'last'" />
</div>
- 代碼重復,不夠優(yōu)雅
- <el-upload />上屬性多,后期維護,改了第一個組件,容易漏掉最后一個組件,造成bug
(2)為了解決代碼重復的問題,在想到將<el-upload />組件封裝成組件,不失為一個好辦法,
但是由于<el-upload />上屬性太多,要寫很多prop。
(3)在進一步思考,在本組件內(nèi),可操作DOM,達到移動的目的。上面兩個問題都可以解決
onMounted(() => {
if (props.position === 'last') {
const container: any = document.getElementById('wrapper')
const firstItem: any = container.firstChild
container.appendChild(firstItem)
}
})
在vue中操作DOM的代碼要寫在onMounted中,此時組件掛載完成,DOM可確保獲取到。
操作DOM需要三步:
- 獲取div父元素:通過document.getElementById獲取div元素
- 獲取上傳按鈕卡片:通過firstChild屬性,獲取上傳卡片按鈕
- 移動:在通過appendChild方法移動到div的末尾
DOM操作步驟確定,滿足上面三步的方法,還可以變換,比如:
onMounted(() => {
if (props.position === 'last') {
const container: any = document.querySelector("#wrapper")
const firstItem: any = container.childNodes[0]
container.insertBefore(firstItem, null)
}
})
- 獲取div父元素:通過document.querySelector獲取div元素
- 獲取上傳按鈕卡片:通過childNodes屬性的,獲取上傳卡片按鈕
- 移動:在通過insertBefore方法,將第一個元素插入到最后
三、DOM方法整理
appendChild():用于向元素的末尾添加一個節(jié)點
insertBefore():把節(jié)點放在元素中某個特定的位置上
replaceChild():替換子元素中某個節(jié)點
cloneNode():復制一個節(jié)點
const container: any = document.getElementById('wrapper')
container.appendChild(newNode)
container.insertBefore(newNode, targetNode)
container.replaceChild(newNode, targetNode)
container.cloneNode()
到此這篇關于Vue操作DOM解決顯示位置問題的文章就介紹到這了,更多相關Vue DOM顯示位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue中的data,computed,methods,created,mounted用法及說明
這篇文章主要介紹了vue中的data,computed,methods,created,mounted用法及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
關于vue-property-decorator的基礎使用實踐
這篇文章主要介紹了關于vue-property-decorator的基礎使用實踐,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08

