vue를 사용하여 다른 페이지로 라우팅하고 해당 페이지의 제목과 텍스트를 표시하는 방법은 무엇입니까?
저는 vue에 게시물 사이트를 만들고 있습니다.이게 제 고민이에요.
모든 블로그를 위한 페이지와 블로그를 볼 수 있는 페이지가 있습니다.저는 vuex를 사용하고 있습니다.블로그 중 하나를 클릭하면 뷰블로그 페이지로 이동하여 올바른 블로그 제목을 볼 수 있으므로 문제 없습니다.
내가 하고 싶은 일은 간단해 보인다.제목과 텍스트 두 가지 항목이 있는 뷰블로그 페이지를 원합니다.이 두 개는 매장(vuex)에서 구입해야 합니다.
현재 뷰블로그 페이지는 다음과 같습니다.
<template>
<div class="post">
<h1>{{ $route.params.title }}</h1>
// here I want my text from the store.
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
그리고 이것은 도서관입니다.
<template>
<div class="card-wrapper">
<Card :post="post" v-for="(post, index) in cards" :key="index" />
</div>
</template>
<script>
import Card from "../components/Card.vue";
export default {
components: {
Card,
},
computed: {
cards() {
return this.$store.state.cards;
},
},
};
</script>
<style>
// ...
</style>
도서관에는 카드가 있습니다.
<template>
<div class="card">
<router-link
:post="post"
:to="{ name: 'Post', params: { id: post.index, title: post.title } }"
>
<div class="image"></div>
<div class="title">{{ post.title }}</div>
</router-link>
</div>
</template>
<script>
export default {
name: "Card",
props: ["post"],
};
</script>
<style>
// ...
</style>
이것은 나의 vue-router입니다.
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
},
{
path: '/post/:id',
name: 'Post',
component: () => import('../views/Post.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
router.beforeEach((to, from, next) => {
console.log(to)
let documentTitle = `${ process.env.VUE_APP_TITLE } - ${to.name}`
if (to.params.title) {
documentTitle += ` - ${ to.params.title }`
}
document.title = documentTitle
next()
})
export default router
마지막으로 스토어(vuex):
import { createStore } from "vuex";
export default createStore({
state: {
cards: [{
title: "Blog 1",
text: "This is blog 1",
index: 1,
},
{
title: "Blog 2",
text: "This is blog 2",
index: 2,
},
{
title: "Blog 3",
text: "This is blog 3",
index: 3,
},
{
title: "Blog 4",
text: "This is blog 4",
index: 4,
},
{
title: "Blog 5",
text: "This is blog 5",
index: 5,
},
{
title: "Blog 6",
text: "This is blog 6",
index: 6,
},
{
title: "Blog 7",
text: "This is blog 7",
index: 7,
},
],
},
mutations: {},
actions: {},
modules: {},
});
이것은 라이브러리의 결과입니다.그리고 이것은 뷰 블로그 페이지에 있는 결과입니다.블로그 1: 명확성을 위해:제목 아래에는 스토어에서 온 텍스트가 표시됩니다. 이 예에서는 이 텍스트가 This is blog 1
도와줘서 고마워요!
접근법 1: 패스 바이 루트 파라미터
getter 함수를 정의하여 지정된 블로그 텍스트를 선택할 수 있습니다.패스 더:id
blog-route
로 param
할 수 getter
겟터는 이같같으로 을 했다.forEach
어레이를 필터링 하는 다른 옵션이 있습니다.필요에 맞는 옵션을 선택합니다.
component
할 수 postgetter의 합니다.
VueX 스토어
import { createStore } from 'vuex';
export default createStore({
state: {
cards: [{
title: "Blog 1",
text: "This is blog 1",
index: 1,
},
{
title: "Blog 2",
text: "This is blog 2",
index: 2,
},
{
title: "Blog 3",
text: "This is blog 3",
index: 3,
},
{
title: "Blog 4",
text: "This is blog 4",
index: 4,
},
{
title: "Blog 5",
text: "This is blog 5",
index: 5,
},
{
title: "Blog 6",
text: "This is blog 6",
index: 6,
},
{
title: "Blog 7",
text: "This is blog 7",
index: 7,
},
],
},
getters: {
blogTextById: (state) => (index) => {
let foundText;
state.cards.forEach((card) => {
// cast both indexes to Number, so that we won't run into
//unexpected type-mismatch. Since index might be coming
// from an URL, it's likely that it is stored as a splitted
// string, holding only a number.
// e.g.: index = "2" instead of index = 2
if (Number(card.index) === Number(index)) foundText = card.text;
});
return foundText;
},
},
});
ViewBlog 컴포넌트
<template>
<div class="post">
<h1>{{ $route.params.title }}</h1>
<p>{{ blogText }}</p>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters({
blogTextGetter: 'blogTextById',
}),
blogText() {
return this.blogTextGetter(this.$route.params.id);
},
},
}
</script>
접근법 2: ID를 소품으로 전달하고 카드 전체를 취득합니다.
이 방법에는 몇 가지 변경이 더 필요하며, 그 중 일부는 경로의 매개 변수를 사용하는 일반적인 방법을 변경합니다. to we we we we we we 。viewBlogPage
은 단지 '아예'를 것입니다.id || index
이치노그런 다음 이 ID를 사용하여 카드 항목 전체를 가져오고 표시할 모든 데이터를 표시합니다.
고객님의 고객명LibraryCardComponent
에 「루트 콜」을 .title
param,으로 나쁜 관행은 이 에 따라가기가 .와 컴포넌트 간의 됩니다.$route
물건.하지만 당신이 그것을 사용하고 있기 때문에beforeEach
훅은 그대로 두겠습니다.
따라서 우리는 어떻게 해야 할까요?
합니다.Post
구성요소를 라우팅하기 위해 소품 통과를 활성화하려면
루트 정의
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
},
{
path: '/post/:id',
name: 'Post',
// Here we enable the passing of props.
// The boolean mode passes all params defined as props with the same name as the param
// So :id will be available as prop 'id' in the Component.
props: true,
component: () => import('../views/Post.vue')
}
]
이제 나중에 사용할 수 있도록 소품을 컴포넌트에 도입해야 합니다.
ViewBlog Page
<template>
<div class="post">
<h1>{{ blogPost.title }}</h1>
<p>{{ blogPost.text }}</p>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
props: {
id: {
required: true,
}
},
computed: {
...mapGetters({
blogById: 'blogById',
}),
blogPost() {
return this.blogById(this.id);
},
},
}
</script>
접근법의 getter는 getBlogText Getter가 아닌 getBlog Getter로 쓸 수 있습니다.
VueX 게터
import { createStore } from 'vuex';
export default createStore({
state: {
cards: [{
title: "Blog 1",
text: "This is blog 1",
index: 1,
},
{
title: "Blog 2",
text: "This is blog 2",
index: 2,
},
{
title: "Blog 3",
text: "This is blog 3",
index: 3,
},
{
title: "Blog 4",
text: "This is blog 4",
index: 4,
},
{
title: "Blog 5",
text: "This is blog 5",
index: 5,
},
{
title: "Blog 6",
text: "This is blog 6",
index: 6,
},
{
title: "Blog 7",
text: "This is blog 7",
index: 7,
},
],
},
getters: {
blogById: (state) => (index) => {
// cast both to Number() to prevent unexpected type-mismatch
return state.cards.find(c => Number(c.index) === Number(index));
},
},
});
에서는, 「 」를 참조해 주세요.title
★★★★★★★★★★★★★★★★★」text
표시는 루트 파라미터와 밀접하게 결합되지 않고 vueX로부터의 상태와 반응적으로 결합됩니다.
두 가지 방법 중 하나가 당신의 요구에 맞기를 바랍니다.
언급URL : https://stackoverflow.com/questions/70197962/how-to-use-vue-to-route-to-different-pages-and-display-their-title-and-text
'programing' 카테고리의 다른 글
stdout과 STDOUT_FILENO의 차이점 (0) | 2022.07.21 |
---|---|
Vuex에서 Vue 라우터 파라미터를 취득하는 방법 (0) | 2022.07.21 |
어레이 요소를 제거하지 못했습니다. (0) | 2022.07.21 |
다른 getter에 의존하는 Vuex getter 단위 테스트 (0) | 2022.07.21 |
Mockito를 사용하여 특정 메서드가 호출되지 않았는지 확인하는 방법 (0) | 2022.07.21 |