Detailed explanation of the mounted life cycle function in Vue
In Vue, the life cycle function of the component is one of the very important parts. One of the important life cycle functions is mounted. This life cycle function will be called after the Vue instance is created, that is, after the component is mounted on the page. Let's discuss the use and role of the mounted life cycle function in detail.
The role of the mounted life cycle function
The mounted life cycle function is called after the component is mounted on the page. It indicates that the component has been initialized and the template has been rendered into a real DOM. Therefore, the real DOM can be accessed and manipulated in the mounted life cycle function, and some initialization operations can be performed.
Specific application scenarios
mounted() { axios.get('/api/data') .then(response => { this.data = response.data; }) .catch(error => { console.error(error); }); }
In the above example, we send an asynchronous request through the axios library, and then update the data returned by the backend to the data attribute of the component. In this way, we can ensure that the data has been obtained when the component is initialized.
mounted() { const button = document.querySelector('.my-button'); button.addEventListener('click', this.handleClick); }, methods: { handleClick() { console.log('按钮被点击!'); } }
In the above example, we selected a button element with class 'my-button' through querySelector in the mounted life cycle function, and added a click event listener for it . When the button is clicked, the handleClick method defined in the component will be called, and finally the console output 'Button was clicked! '.
mounted() { $('.slider').slider(); // 或者 const myComponent = new MyComponent(); myComponent.init(); }
In the above example, we use jQuery's .slider() method to initialize the element with class 'slider' into a slider, or we use the init method of the custom component MyComponent Perform initialization operations.
Summary
The mounted life cycle function plays a very important role in the Vue component. It marks that the component has been initialized and can perform some operations related to DOM, asynchronous requests, third-party libraries, etc. By flexibly using the mounted lifecycle function, we can better control the initialization process of the component and provide users with a better interactive experience.
I hope this article can be helpful to the use of the mounted life cycle function in Vue, allowing you to operate and control your Vue components more flexibly.
The above is the detailed content of Detailed explanation of mounted life cycle function in Vue. For more information, please follow other related articles on the PHP Chinese website!