2025-01-15 06:00:57 +03:00

151 lines
3.3 KiB
Vue

<template>
<div class="app">
<h1>Страница постов</h1>
<my-input v-model="searchQuery" placeholder="Поиск" class="search"/>
<div class="app__btns">
<my-button @click="showCreateDialog" class="createBtn">
Создать пост
</my-button>
<my-select v-model="selectedSort" :options="sortOptions"/>
</div>
<my-dialog v-model:show="dialogVisible">
<post-form @createPost="createPost" />
</my-dialog>
<div v-if="isPostLoading" style="margin-top: 15px">Loading...</div>
<post-list v-else :posts="sortedAndSearchedPosts" @removePost="removePost" class="postList"/>
<my-pagination
:currentPage="page"
:totalPages="totalPages"
@changePage="changePage"
/>
</div>
</template>
<script>
import PostForm from '@/components/PostForm.vue';
import PostList from '@/components/PostList.vue';
import axios from 'axios';
import MyPagination from '@/components/ui/Pagination.vue';
export default {
components: {
MyPagination,
PostForm,
PostList
},
data() {
return {
posts: [],
dialogVisible: false,
isPostLoading: false,
selectedSort: '',
sortOptions: [
{value: 'title', name: 'По названию'},
{value: 'body', name: 'По описанию'}
],
searchQuery: '',
page: 1,
limit: 10,
totalPages: 0
}
},
methods: {
createPost(newPost) {
this.posts.push(newPost);
this.dialogVisible = false;
},
removePost(post) {
this.posts = this.posts.filter(p => p.id !== post.id)
},
showCreateDialog() {
this.dialogVisible = true;
},
async fetchPosts() {
try {
const { data, headers } = await axios.get(`https://jsonplaceholder.typicode.com/posts`, {
params: {
_limit: this.limit,
_page: this.page
}
});
this.posts = data;
this.totalPages = Math.ceil(headers['x-total-count'] / this.limit);
} catch (e) {
alert(e.message);
}
},
changePage(newPage) {
this.page = newPage;
}
},
async mounted() {
this.isPostLoading = true;
await this.fetchPosts()
this.isPostLoading = false
},
computed: {
sortedPost() {
return [...this.posts].sort((post1, post2) => {
return post1?.[this.selectedSort]?.localeCompare(post2?.[this.selectedSort])
})
},
sortedAndSearchedPosts() {
return this.sortedPost.filter((post) => post.title.toLowerCase().includes(this.searchQuery.toLowerCase()))
}
},
watch: {
// selectedSort(newValue) {
// this.posts.sort((post1, post2) => {
// return post1[newValue].localeCompare(post2[newValue])
// })
// },
dialogVisible(newValue) {
if (newValue) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = 'auto';
}
},
page() {
this.fetchPosts()
}
}
}
</script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.app {
padding: 20px;
}
.createBtn {
margin-top: 15px;
}
.postList {
margin-top: 15px;
}
.app__btns {
display: flex;
justify-content: space-between;
align-items: center;
}
.search {
margin-top: 15px;
}
</style>