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>
到此这篇关于Vue3获取和操作DOM元素的项目实践的文章就介绍到这了,更多相关Vue3获取和操作DOM内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
详解在vue-cli中引用jQuery、bootstrap以及使用sass、less编写css
这篇文章主要介绍了详解在vue-cli中引用jQuery、bootstrap以及使用sass、less编写css,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-11-11
基于el-table和el-pagination实现数据的分页效果
本文主要介绍了基于el-table和el-pagination实现数据的分页效果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-08-08
vue3使用拖拽组件draggable.next的保姆级教程
做项目的时候遇到了一个需求,拖拽按钮到指定位置,添加一个输入框,这篇文章主要给大家介绍了关于vue3使用拖拽组件draggable.next的保姆级教程,需要的朋友可以参考下2023-06-06
vue2结合element-ui的gantt图实现可拖拽甘特图
因为工作中要用到甘特图,所以我在网上搜索可以用的甘特图,搜索了好多,但是网上搜到大多数都很鸡肋,不能直接使用,下面这篇文章主要给大家介绍了关于vue2结合element-ui的gantt图实现可拖拽甘特图的相关资料,需要的朋友可以参考下2022-11-11


最新评论