Home  >  Article  >  Web Front-end  >  What does ref in vue mean?

What does ref in vue mean?

下次还敢
下次还敢Original
2024-05-02 20:42:15815browse

The ref attribute in Vue allows developers to access the DOM element or instance of a component. Uses include: directly manipulating DOM elements, such as setting focus or getting values. Access component instances to get data or call methods. Establish relationships between components, such as parent-child communication.

What does ref in vue mean?

ref in Vue

ref is an important feature in Vue.js, which allows developers to access The DOM element or instance of the component.

Uses

ref can be used in the following scenarios:

  • Directly manipulate a DOM element, such as setting focus or getting its value.
  • Access the component instance, such as getting its data or calling its methods.
  • Establish relationships between components, such as using references to create parent-child component communication.

Syntax

ref can be used in the following ways:

<code class="html"><template>
  <input ref="myInput" />
</template>

<script>
export default {
  mounted() {
    // 获取 DOM 元素
    this.$refs.myInput.focus();
  }
};
</script></code>

Assignment

ref Assigned to a DOM element or instance of the component, depending on whether it is used in a template or script.

  • In a template, ref refers to a DOM element.
  • In scripts, ref refers to component instances.

Access

You can access ref through the $refs object:

<code class="js">this.$refs.myInput // 返回 DOM 元素
this.$refs.myComponent // 返回组件实例</code>

Note

  • ref names must be unique.
  • Ref can only be used after DOM rendering is completed.
  • ref cannot be used in asynchronous or functional components.

The above is the detailed content of What does ref in vue mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn