Home >Web Front-end >Vue.js >How to use mounted in vue

How to use mounted in vue

下次还敢
下次还敢Original
2024-05-08 17:09:181134browse

The mounted hook of Vue.js is called after the component is inserted into the DOM for the first time and is used to perform: 1. AJAX request; 2. Initialize third-party library; 3. Element operation; 4. Event subscription; 5. Timing device settings. Specific examples include getting data, setting event listeners, initializing jQuery, etc.

How to use mounted in vue

mounted usage in Vue

mounted is an important method in the Vue.js life cycle hook. It will Called after the component is inserted into the real DOM for the first time. This method is used to perform some additional operations after the component is mounted, for example:

1. AJAX request

You can initiate an AJAX request in mounted to obtain from the server data. This is useful for dynamically populating data as the component loads.

2. Initialize third-party libraries

You can use the mounted method to initialize third-party libraries, such as jQuery or D3. It ensures that these libraries are not initialized until the component is rendered.

3. Element operations

You can directly operate DOM elements in mounted, such as setting event listeners or getting element dimensions. Doing this improves performance because these operations are only performed the first time the component is rendered.

4. Subscribing to events

You can use mounted to subscribe to events in other components or Vuex storage. This enables communication between different components or between components and storage.

5. Timers and Intervals

You can set timers or intervals in mounted to perform tasks regularly. This is useful for updating component state or triggering other actions.

Example usage:

<code class="javascript">mounted() {
  // 发起 AJAX 请求
  this.$http.get('/api/data').then(response => {
    this.data = response.data;
  });

  // 初始化 jQuery
  $(this.$refs.container).draggable();

  // 订阅事件
  this.$on('update-data', () => {
    this.$http.get('/api/data').then(response => {
      this.data = response.data;
    });
  });

  // 设置定时器
  setTimeout(() => {
    this.message = '欢迎使用 Vue.js!';
  }, 1000);
}</code>

It should be noted that the mounted method will only be called after the component is inserted into the real DOM for the first time. This method will not be called if the component is re-rendered or reinserted into the DOM.

The above is the detailed content of How to use 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
Previous article:The role of $mount in vueNext article:The role of $mount in vue