Vue3如何获取和操作DOM元素

环境:vue3+ts+vite
目标:
1.修改DOM的文本值和样式
2.获取后代子DOM元素,操作修改

<template>
    <div class="content">
        <h1>演示</h1>
        <p ref="pText1">这是ref为pText1的一段文本</p>
    </div>
</template>
<script lang="ts" setup>
import {ref} from 'vue'
const pText1=ref()
console.log(pText1.value)

</script>

在这里插入图片描述

发现此时定义的pText1打印的值是undefined,这个情况发生原因是未真正获取到DOM元素,并不是我们定义的const pText1=ref()里面是空的问题。于是在生命钩子里面执行看看是什么?

<template>
    <div class="content" style="padding: 0 30px;">
        <h1>演示</h1>
        <p ref="pText1">这是ref为pText1的一段文本</p>
    </div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue'
const pText1=ref()
console.log(pText1.value)
onMounted(()=>{
    console.log(pText1.value)
})
</script>

在这里插入图片描述

看到了吧。那接下来就知道怎么操作了,加一下颜色

onMounted(()=>{
    console.log(pText1.value)
    pText1.value.style.color='red'
})

在这里插入图片描述
再改个文本值看看

onMounted(()=>{
    console.log(pText1.value)
    pText1.value.style.color='red'
    pText1.value.innerText='我是修改后的文本值'
})

在这里插入图片描述
当然,我们不一定要页面加载就执行,我们可以定义一个方法来执行DOM修改操作:

<template>
    <div class="content" style="padding: 0 30px;">
        <h1>演示</h1>
        <p ref="pText1">这是ref为pText1的一段文本</p>
        <el-button @click="changeText" type="primary">点我修改</el-button>
    </div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue'
const pText1=ref()
const changeText=()=>{
    console.log(pText1.value)
    pText1.value.style.color='red'
    pText1.value.innerText='我是点击后修改的文本值'
}
/*onMounted(()=>{
    console.log(pText1.value)
    pText1.value.style.color='red'
    pText1.value.innerText='我是修改后的文本值'
})*/
</script>

点击按钮前:
在这里插入图片描述
点击按钮后:
在这里插入图片描述

获取后代子DOM元素,操作修改

<template>
    <div class="content" style="padding: 0 30px;">
        <h1>演示</h1>
        <p ref="pText1">这是ref为pText1的一段文本 <span>aaaaaaa</span></p>
    </div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue'
const pText1=ref()
onMounted(()=>{
    //console.log(pText1)
    console.log(pText1.value.children[0].innerHTML)
    pText1.value.children[0].style.color='red';
    pText1.value.children[0].innerText='我是修改后的span的文本';
})
</script>

在这里插入图片描述
总之,想要获取DOM元素属性,可以先打印出来,按需取值即可:

<template>
    <div class="content" style="padding: 0 30px;">
        <h1>演示</h1>
        <p ref="pText1">这是ref为pText1的一段文本 <span>aaaaaaa</span></p>
    </div>
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue'
const pText1=ref()
onMounted(()=>{
    console.log(pText1)
})
</script>

在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐