JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.11/vue.global.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/4.0.0/vuex.global.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/element-plus/1.0.2-beta.71/index.full.min.js"></script>
<div id="app">
<el-pagination
v-model:current-page="currentPage"
:page-count="$store.state.pages"
layout="prev, pager, next"
background
></el-pagination>
<div v-loading="$store.state.loading">
<div
v-for="n in $store.state.characters"
v-text="n.name"
:key="n.id"
class="character"
></div>
</div>
</div>
CSS
@import url(https://cdnjs.cloudflare.com/ajax/libs/element-plus/1.0.2-beta.71/theme-chalk/index.min.css);
.character {
font-family: monospace;
margin: 10px;
padding: 10px;
border: 1px solid silver;
}
JavaScript
const BASE_URL = 'https://rickandmortyapi.com/api/character';
const store = Vuex.createStore({
state: {
characters: [],
page: 0,
pages: 0,
loading: false,
},
mutations: {
setLoading: (state, loading) => state.loading = loading,
setCharacters: (state, { characters, pages, page }) =>
Object.assign(state, { characters, pages, page }),
},
actions: {
async fetchCharacters({ state, commit }, page = 1) {
commit('setLoading', true);
// это чтобы индикатор загрузки немного покрутился
await new Promise(r => setTimeout(r, 1000));
try {
const { data: { info, results } } = await axios.get(`${BASE_URL}?page=${page}`);
commit('setCharacters', {
page,
pages: info.pages,
characters: results,
});
} catch (e) {
console.error(e);
}
commit('setLoading', false);
},
},
});
Vue.createApp({
computed: {
currentPage: {
get() {
return this.$store.state.page;
},
set(page) {
this.$store.dispatch('fetchCharacters', page);
},
},
},
created() {
this.currentPage = 1;
},
})
.use(store)
.use(ElementPlus)
.mount('#app');