How to use Vue.js lifecycle hooks like created and mounted?

Vue.js provides several lifecycle hooks that allow you to execute code at different stages of a component's lifecycle. Two of the most commonly used hooks are created and mounted.

created: This hook is called when the component has been created, but it has not yet been mounted to the DOM. You can use this hook to perform initial data setup, such as fetching data from an API or setting up event listeners.

Here's an example of using the created hook:

export default { created() { // Perform initial data setup this.fetchData(); // Set up event listener window.addEventListener('resize', this.handleResize); }, methods: { fetchData() { // Fetch data from API }, handleResize() { // Handle window resize event } } }

mounted: This hook is called when the component has been mounted to the DOM. You can use this hook to interact with the rendered DOM elements, such as accessing the DOM using a ref or initializing third-party libraries.

Here's an example of using the mounted hook:

export default { mounted() { // Access DOM element using ref this.$refs.myElement.innerHTML = 'Hello, Vue!'; // Initialize third-party library this.initializeSlider(); }, methods: { initializeSlider() { // Initialize a slider using a third-party library } } }

By using these hooks, you can execute code at specific points in a component's lifecycle, which allows you to perform actions like data fetching, event handling, DOM manipulation, and integration with external libraries.