vue获取DOM节点

在vue项目中,获取dom节点可以用ref属性,这个属性就是来获取dom对象的。 这个属性就相当于给这个标签起了一个类似于id的东西。

<template>
    <div class="contaier" ref="box" style="width: 100px;height: 100px;">
        这里用来测试元素的ref属性
    </div>
    <button type="button" @click="showData()">点击</button>
</template>

<script>
    export default {
        methods: {
            showData() {
                console.log(this.$refs.box);
                console.log(this.$refs.box.style);
            }
        }
    }
</script>

显示的结果为:

  1. <div class="container" style="height: 100px; width: 100px;"></div>
    说明:这里获取的是元素本身
  2. 这里获取到了元素的style属性的值在这里插入图片描述
    综上:我们在vue中需要操作某一个元素的时候,可以在元素上添加ref属性,使用$refs来获取到该元素,进而进行一些列操作。
Logo

前往低代码交流专区

更多推荐