Home > Web Front-end > Vue.js > body text

The role of onmounted in vue

下次还敢
Release: 2024-05-09 14:51:19
Original
1037 people have browsed it

onMounted is the component mounting life cycle hook in Vue. Its function is to perform initialization operations after the component is mounted to the DOM, such as obtaining references to DOM elements, setting data, sending HTTP requests, and registering event listeners. wait. It is only called once when the component is mounted. If you need to perform operations after the component is updated or before it is destroyed, you can use other lifecycle hooks.

The role of onmounted in vue

The role of onMounted in Vue

onMounted is one of the Vue life cycle hooks, indicating that the component is mounted to Called after DOM. Its main function is:

Perform operations related to component mounting

After the component is mounted to the DOM, you can perform some initialization operations, such as:

  • Get the reference of the DOM element
  • Set data or attributes
  • Send HTTP request
  • Register event listener

Complete data requests or asynchronous operations

If you need to obtain data or perform operations that take time after the component is mounted, you can do it in the onMounted hook. This ensures that when the data or operation is complete, the component responds accordingly.

For example:

<code class="javascript"><script>
import { onMounted } from 'vue'

export default {
  onMounted() {
    // 获取 DOM 元素的引用
    const el = this.$refs.myElement

    // 设置数据
    this.data = 'Hello world!'

    // 发送 HTTP 请求
    fetch('https://example.com/api/data').then((response) => {
      this.data = response.data
    })

    // 注册事件监听器
    window.addEventListener('resize', this.onResize)
  },
  methods: {
    onResize() {
      // 窗口大小改变时响应
    }
  }
}
</script></code>
Copy after login

Note:

  • onMounted hook is only called once when the component is mounted.
  • If you need to perform an operation after the component is updated, you can use the onUpdated hook.
  • If you need to perform cleanup operations before the component is destroyed, you can use the onBeforeUnmount hook.

The above is the detailed content of The role of onmounted in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template