卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章75224本站已运行4311

vue3怎么获取dom

在 vue 3 中,通过 ref 属性获取 dom 元素或组件实例:添加 ref 属性,指定唯一名称。在组件中使用 useref() 钩子创建引用,与 ref 属性绑定。通过 ref 属性访问 dom 元素或组件实例,获取其值。

vue3怎么获取dom

Vue 3 中如何获取 DOM

在 Vue 3 中,可以通过 ref 属性来获取 DOM 元素或组件实例。

步骤:

  1. 向模板添加 ref 属性: 为需要获取的 DOM 元素或组件添加 ref 属性,并指定一个唯一的名称。
  2. 在组件中使用 ref: 在组件的 setup() 方法中,使用 useRef() 钩子创建引用,并将其与 ref 属性绑定的名称关联。

示例:

获取一个按钮元素:

<template><button ref="submitButton">提交</button>
</template><script>
import { useRef } from 'vue';

export default {
  setup() {
    const submitButtonRef = useRef();

    // 访问 DOM 元素
    // ...

    return {
      submitButtonRef,
    };
  },
};
</script>

获取一个组件实例:

<template><customcomponent ref="customComponent"></customcomponent></template><script>
import { useRef } from 'vue';
import CustomComponent from './CustomComponent.vue';

export default {
  setup() {
    const customComponentRef = useRef();

    // 访问组件实例
    // ...

    return {
      customComponentRef,
    };
  },
};
</script>

访问 DOM 元素或组件实例

一旦创建了引用,就可以通过 ref 属性访问 DOM 元素或组件实例:

立即学习“前端免费学习笔记(深入)”;

// 获取按钮元素
const submitButtonEl = this.submitButtonRef.value;

// 获取组件实例
const customComponentInstance = this.customComponentRef.value;

在上述示例中,submitButtonEl 引用了按钮元素,customComponentInstance 引用了 CustomComponent 组件的实例。

卓越飞翔博客
上一篇: vue3怎么获取插槽中的数据
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏