This Vue.js code snippet illustrates how to fetch and render a list of items from a provided URL. This is a common operation in web applications, such as displaying a list of recipes or a to-do list.

Code Snippet

<template>
  <div>
    <p v-for="item in list" :key="item.id">{{ item.name }}</p>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  props: ['url'],
  data () {
    return {
      list: []
    };
  },
  async mounted () {
    const { data } = await axios.get(this.url)
    this.list = data
  }
};
</script>

Explanation

In this Vue component, the props option is used to accept a url prop from a parent component. The data function returns an object that contains a list array.

The mounted lifecycle hook, which is executed after the component is mounted to the DOM, is used to fetch data from the provided URL using the Axios library. The fetched data is then assigned to the list array.

In the template, the v-for directive is used to loop over the list array and render a paragraph (<p>) element for each item in the list.

Usage

To use this Vue component, you need to have Vue.js and Axios installed in your project. You can install Axios using npm with the command npm install axios.

You can use this component in any part of your Vue application by passing the desired API endpoint URL as a prop to the component.

Example

Suppose you want to fetch a list of recipes from an API endpoint and display them in your Vue application. You can use this component and pass the API endpoint URL as a prop.

Conclusion

This Vue.js code snippet simplifies the task of fetching and displaying a list of items from an API.

This is commonly required in many web applications, like showing a list of recipes, a to-do list, or any other list-based data.

The component can be easily reused across different parts of your Vue application by passing different API endpoints.