@sanek3275

Как обновить router-view при переходе страницы в Vue3?

Здравствуйте, начал изучать Vue3. Столкнулся с проблемой пагинации. При нажатий на кнопки страниц, ни чего не происходит. Хотелось бы чтоб при нажатий выбора страницы и потом при выборе пункта меню (которое будет с права).
перезагружалась и выводила новые данные.
<template>
	<HeiderPortfoli :img='"/../public/macbook.jpg"' :title='"Портфолио"' contents="текст" :arts="0" />
	<section class="portfolio_section bg0 bg1 ">
		<div class="portfolio_page">
			<div class="portfolio_items">
				<router-view />
				<template v-for="item  in  portfolio.post " :key="item.ID">
					<CardPortfolio :url="item.post_name" :img="item.img" :title="item.post_title"
						:content="item.post_content" :color="item.color" />
				</template>
			</div>
			<div class="portfolio_seadbar">
меню
			</div>
		</div>
		<div v-if="portfolio.max_num_pages != 0 || portfolio.max_num_pages != null">
			<ul class="pagination">
				<template v-for="n in portfolio.max_num_pages" :key="n">
					<template v-if="n == portfolio.page">
						<span class="active">{{ n }}</span>
					</template>
					<template v-else>
						<router-link :to="{ name: 'portfolio', params: { page: n } }">{{ n }}</router-link>
					</template>
				</template>
			</ul>
		</div>
	</section>
</template>
<script>
function pereborpage(no) {
	var hop = 0;
	if (no == 0) {
		hop = 1;
	} else {
		hop = no;
	}
	return hop;
}
import HeiderPortfoli from '@/components/HeiderPortfoli.vue';
import CardPortfolio from '@/components/CardPortfolio.vue';
export default {
	name: 'ServicesV',
	components: {
		HeiderPortfoli,
		CardPortfolio
	},
	data() {
		return {
			portfolio: [],
			my: [],
			cms: [],
			n: 0,
			page: 1,
		};
	},
	async mounted() {

		const lrt = this.$route.params.page;
		const ThisPage = pereborpage(lrt);
		console.log(this.$route);
		console.log(lrt);
		console.log(ThisPage);
		this.page = ThisPage;
		const portfolioj = await fetch(`API?page=${this.page}`);
	}
}
</script>
  • Вопрос задан
  • 173 просмотра
Пригласить эксперта
Ответы на вопрос 1
@sanek3275 Автор вопроса
После того как Aetae на мекнул на JS. Я вспомнил про событие, с помощь их отловил событие клика и с кнопками пагинации это работало. Но мне нужно было отслеживать событие в других компонентах. Не знаю правильно ли я сделал, но я обратился к VUEX. Сейчас код выглядит так

/store/index.js
import { createStore } from 'vuex'

const store = createStore({
	state: {
		page: 1,
		maxpage: 1,
		newmenu: false,
		portfolio: [],
	},
	mutations: {
		INCREMENT_PAGE(state, payload) {
			state.page = payload;
			console.log(state.page);
		},
		INCREMENT_PORTFOLIO(state, payload) {
			state.portfolio = payload;
			console.log(state.portfolio);
		},
		INCREMENT_MAXPAGE(state, payload) {
			state.maxpage = payload;
			console.log(state.maxpage);
		},
	}
})

export default store;


/src/views/PortfolioViem.vue
<template>
	<section class="portfolio_section bg0 bg1 ">
		<div class="portfolio_page">
			<div class="portfolio_items">
				<PortFolioList :page='this.$store.state.page' />
			</div>
			<div class="portfolio_seadbar">
			</div>
		</div>
		{{ my }}
		<Pagination :max_num_pages='portfolio.max_num_pages' :pages='this.$store.state.page' />
	</section>
</template>
<script>
function pereborpage(no) {
	var hop = 0;
	if (no == 0 || no == null) {
		hop = 1;
	} else {
		hop = no;
	}
	return hop;
}
import HeiderPortfoli from '@/components/HeiderPortfoli.vue';
import PortFolioList from '@/components/PortfolioList.vue';
import Pagination from '@/components/Pagination.vue';
export default {
	name: 'ServicesV',
	components: {
		HeiderPortfoli,
		PortFolioList,
		Pagination
	},
	data() {
		return {
			portfolio: [],
			my: [],
			cms: [],
			n: 0,
			page: 1,
		};
	},
	async mounted() {
		console.log(this.$store.state.page)
		const lrt = this.$route.params.page;
		const ThisPage = pereborpage(lrt);
		this.$store.commit('INCREMENT_PAGE', ThisPage);
		console.log(this.$route);
		console.log(lrt);
		console.log(ThisPage);
		this.page = ThisPage;
		const my_servecj = await fetch('API/my_servec/');
		const cms_servesj = await fetch('API/cms_serves/');
		const my_servecq = await my_servecj.json();
		const cms_servesq = await cms_servesj.json();
		this.my = my_servecq;
		this.cms = cms_servesq;
	}
}
</script>


/src/components/Pagination.vue
<template>
	<div v-if="this.$store.state.maxpage != 0 || this.$store.state.maxpage != null">
		<ul class="pagination">
			<template v-for="n in this.$store.state.maxpage" :key="n">
				<template v-if="n == page">
					<span class="active">{{ n }}</span>
				</template>
				<template v-else>
					<router-link @:click="perexod(n)" :to="{ name: 'portfolio', params: { page: n } }">{{ n }}</router-link>
				</template>
			</template>
		</ul>
	</div>
</template>

<script >
export default {
	name: 'PaginationV',
	data() {
		return {
			n: 0,
			page: 1,
			portfolioj: [],
		}
	},
	props: {
		max_num_pages: Number,
		pages: Number,
	},
	methods: {
		async perexod(pag) {
			//console.log(pag);
			this.page = pag;
			this.$store.commit('INCREMENT_PAGE', pag);
			const portfolioj = await fetch(`api/?page=${this.$store.state.page}`);
			const portfolioq = await portfolioj.json();
			this.$store.commit('INCREMENT_PORTFOLIO', portfolioq.post);
			this.$store.commit('INCREMENT_MAXPAGE', portfolioq.max_num_pages);
			//console.log(this.page);
			console.log(this.$store.state.page);
		}
	},
}
</script>

<style scoped>

/src/components/PortfolioList.vue

<template>
	<template v-for="item  in  this.$store.state.portfolio " :key="item.ID">
		<CardPortfolio :url="item.post_name" :img="item.img" :title="item.post_title" :content="item.post_content"
			:color="item.color" />
	</template>
</template>

<script>
import CardPortfolio from '@/components/CardPortfolio.vue';
export default {
	name: 'PortFolioList',
	props: {
		type: Number,
		page: Number,
	},
	components: {
		CardPortfolio
	},
	data() {
		return {
			portfolio: [],
		};
	},
	async mounted() {
		const portfolioj = await fetch(`api/?page=${this.$store.state.page}`);
		const portfolioq = await portfolioj.json();
		this.$store.commit('INCREMENT_PORTFOLIO', portfolioq.post);
		this.$store.commit('INCREMENT_MAXPAGE', portfolioq.max_num_pages);
		console.log(portfolioq);
		this.portfolio = portfolioq;
	}
}
</script>

<style scoped></style>


Все работает, при нажатии выбора страницы. Список обновляется, без самой перезагрузки страницы. Однако мне интересно мнение профи, все ли я сделал правильно ? и можно было как-то по другому? может есть моменты которые можно улучшить ?
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы