게시판 만들기 7 - 게시글 상세보기(onethejay님)
언제나와 같이 위 링크 참조해서...
라고는 했지만 여러 가지로 바뀐 게 있다.
<router-link :to="`/board/post/${row.boardIdx}`">
일단 게시글 이동을 함수가 아닌 rounter-link로 위와 같이 처리했다.
routes/index.js에서는 nested router 써서 게시판 목록과 상세를 /board/ 이하에서 한번에 볼 수 있게 해두고...
// routes/index.js의 해당 부분
{
...
path: '/board',
component: BoardPage,
redirect: '/board/list',
children: [
{
path: 'list',
component: PostListPage
},
{
path: 'post/:idx',
component: PostDetail,
},
],
...
}
게시판 상세 컴포넌트에서는 주소를 받아서 route 객체에 있는 params에서 꺼내서 호출하게 해뒀다.
// 게시글 상세 뷰 인스턴스의 script 부분
<script>
import {fetchPost} from "@/api/board";
import PostList from "@/components/PostList.vue"
export default {
components: {
PostList,
},
data() {
return {
idx: this.$route.params.idx,
post: [],
}
},
mounted() {
this.idx= this.$route.params.idx;
this.getPost(this.idx);
},
updated() {
this.idx = this.$route.params.idx;
},
watch: {
idx: function(value, oldValue) {
console.log(`이전 값 : ${oldValue}, 현재 값 : ${value}`);
this.getPost(value);
}
},
methods: {
async getPost(postIndex) {
const {data:post} = await fetchPost(postIndex);
this.initPost(post);
},
initPost(post) {
this.post=post;
},
},
}
</script>
중간에 updated에서 post 갱신하게 해놨더니 무한루프에 빠져서... 그런데 beforeUpdate에 넣어놓으면 되야할 것 같은데 그건 안되고... 그래서 안 쓰고 싶었는데 그냥 watch를 썼다. 내가 뷰 라이프사이클을 아직도 이해를 잘 못한건지.
그리고 게시글 상세에서도 하단에 게시글 목록 컴포넌트를 삽입해서 목록을 볼 수 있도록 해뒀는데... 나중에 목록을 게시글 앞뒤 글 몇 개만 나타나도록 해둔다든가 현재 게시글은 다르게 표현된다든가 하도록 처리해볼까 싶다.