Vue.js life cycle hook mounted is triggered when the component is first mounted to the DOM and is used to: 1. Obtain DOM element references; 2. Perform initial settings; 3. Ensure DOM stability; 4. Perform asynchronous Task.
The role of mounted in Vue
mounted is one of the Vue.js life cycle hooks. It is used when the component is first mounted. Triggered when loaded into DOM. This means that the component has been initialized, template compiled and rendered, and added to the DOM tree.
The role of mounted
The main purpose of the mounted hook is:
this.$el
Access the root DOM element of the component, allowing interaction and manipulation with the DOM within the component. When to use mounted
Generally, use the mounted hook when:
Example
The following is an example of the mounted hook:
<code class="js">export default { mounted() { // 获取根 DOM 元素的引用 console.log(this.$el); // 初始化组件状态 this.count = 0; // 绑定事件监听器 this.$el.addEventListener('click', this.incrementCount); }, methods: { incrementCount() { // 每次单击按钮时增加计数器 this.count++; } } };</code>
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!