I have many pages with a list of items. Appeal to some api and display the resulting, something like:
Template:
<template> <div class="container"> <div class="row"> <div class="col-12"> <h1>City</h1> <div> <div v-if="errored" class="alert alert-danger"> <p>Произошла ошибка: {{ this.error_text }}</p> </div> <div v-else> <div v-if="loading" class="alert alert-info">Loading...</div> <div v-else> <table class="table"> <tr v-for="item in info" :key="item.id"> <td>{{ item.id }}</td> <td>{{ item.verified }}</td> <td>{{ item.title }}</td> </tr> </table> </div> </div> </div> </div> </div> </div> </template> Script:
<script> import ApiService from '@/services/api'; export default { name: 'City', data() { return { info: null, loading: false, errored: false, error_text: '', }; }, methods: { makeReq: function makeReq() { this.loading = true; ApiService.post('/cityApi/all', {}) .then((response) => { this.info = response.data.cities; }) .catch((error) => { this.errored = true; this.error_text = ApiService.get_error(error); }) .finally(() => { this.loading = false; }); }, }, mounted() { this.makeReq(); }, }; </script> And somehow I recently thought that constantly repeating the same boilerplate in such pages:
- In the template there is always some custom section with a table, and I constantly copy the rest of the binding, with this header and display of load / error
- In the code, I always have the same variables loading, errored and expired with the same values - I would like to declare them once in some basic component and add only new ones if necessary
- The request is exactly the same, always different, except the url
In the guidelines on vue.js I did not come across sections that would help to bring all such uniform code into some basic components and be inherited. How can such a thing be done in vue?
<template src="./hello.html"><template><script></script><style></style>- Dmytryk