Home  >  Article  >  Web Front-end  >  The role of mounted in vue

The role of mounted in vue

下次还敢
下次还敢Original
2024-05-02 20:48:321188browse

mounted is a life cycle hook function in Vue.js, which is triggered immediately after the component is successfully loaded for the first time and inserted into the DOM tree. The functions it provides include: initializing data and status calling API or service binding event listener manipulating DOM setting focus performing other initialization tasks

The role of mounted in vue

##mounted Its role in Vue

mounted is a life cycle hook function in Vue.js, which is triggered immediately after the component is successfully loaded for the first time and inserted into the DOM tree. It provides access to DOM nodes, allowing them to perform specific operations after the component is mounted.

Function:

  • Initialize data and status: You can initialize the data and status of the component to ensure that when the component is mounted in the desired state.
  • Call API or service: You can call API or service and obtain the necessary data after the component is mounted.
  • Bind event listeners: Event listeners can be bound to DOM elements to trigger specific methods when the user interacts.
  • Manipulate DOM: You can directly manipulate DOM nodes, such as adding, deleting or modifying elements.
  • Set focus: You can set the focus of an element in the component.
  • Perform other initialization tasks: You can perform any other initialization tasks that need to be performed after the component is mounted.

Usage:

In the

mounted function of the component, you can perform the required operations as follows:

<code class="javascript">mounted() {
  // 初始化数据和状态
  this.data = { ... };

  // 调用 API
  fetch('/api/data')
    .then(res => this.data = res.data)
    .catch(err => console.error(err));

  // 绑定事件侦听器
  this.$el.addEventListener('click', this.handleClick);

  // 操作 DOM
  this.$el.classList.add('active');

  // 设置焦点
  this.$el.querySelector('input').focus();

  // 其他初始化任务
  console.log('Component mounted!');
}</code>

Note:

  • mounted The hook function is only triggered when the component is mounted for the first time. If the component is later unmounted and remounted, it will not be triggered again.
  • mounted The hook function cannot modify the component's props because the props have been set before the component is created.

The above is the detailed content of The role of mounted in vue. 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