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
##mounted Its role in Vue
mountedis 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:
Usage:
In themountedfunction of the component, you can perform the required operations as follows:
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!'); }
Note:
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.
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!