상세 컨텐츠

본문 제목

[Vue.js] vue route 사용하여 파라미터 전달하기 / 객체(Object) 전달하기

FrontEnd/Vue.js

by SangHoonE 2022. 11. 8. 18:12

본문

반응형

안녕하세요 상훈입니다.

 

Vue.js 3 + Vue Router 를 사용하여 페이지를 넘기고 params에 원하는 값을 전달하는 경우를 포스팅하도록 하겠습니다.

List 화면. Title 항목을 클릭하면, 해당 객체를 가지고 상세페이지로 이동하도록 설정

 

이렇게 컨텐츠 한개가 객체(Object)로 적용하겠습니다.

item : {
	title: 'asdasdasdas',
	content: 'asgasfasf',
	date: new Date()
}

이런식으로 객체는 구성되어있습니다.

string만 데이터를 전달하는것과 거의 동일합니다.

 

1. 데이터를 전달할 Vue파일

//List.vue
<template>
<div v-for="(item, index) in itemList" class="w-full flex">
        <div class="w-8 h-7">{{ index++ }}</div>
        <div class="flex-1" @click="moveToDetail(item)">{{ item.title }}</div>
        <div class="w-32 h-7">{{ item.date }}</div>
</div>
</template>

<script>
...
 methods: {
    moveToDetail(item) {
      this.$router.push({
        name: "ContentDetail",
        params: { item: JSON.stringify(item) },
      });
    },
  },
 ...
 </script>

title을 클릭하면 item 객체를 전달하는 것으로 선언하였습니다.

저기서 item 객체를 문자화 하였는데요.
이유인즉슨, 파라미터를 넘겨줄 때 그냥 넘기게되면 이도저도 안되는 [Object object] 가 넘어옵니다. 
그래서 stringify로 문자화한 후에 내용을 넘깁니다.

 

2. route.js (/route/index.js) -브릿지 역할

 //routes
 
 {
    path: "/ContentDetail/:item",
    name: "ContentDetail",
    component: () => import("../components/Contents/ContentDetail.vue"),
    props: true,
  },
1. path 속성에 :item이라는 key의 이름으로 값을 전달할 것을 지정.
2. props: true  > props를 true로 설정하여 props를 전달할 수 있게 설정하였습니다.

 

3. 전달받을 Vue 파일

<template>
<div>
      <div"> Title: {{ paramObj.title }} </div>
      <div> Content: {{ paramObj.content }} </div>
      <div> date: {{ paramObj.date }} </div>
</div>
</template>

<script>
...

props: {
    item: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      paramObj: {},
    };
  },
  mounted() {
    this.paramObj = JSON.parse(this.$route.params.item);
  },
 
 ...
</script>
1.props로 params를 전달받을 것을 명시
2. item 키를 가진 문자를 받아올 것으로 명시 (JSON.parse를 통해 객체화 실시예정)
3. item 객체를 할당할 ref 선언(data)
4. 컴포넌트가 마운트 완료되고, params 로 받아온 객체를 할당.

 

 

List > Detail 화면
querystring 내용

 

짧지만 긴 포스팅을 마치겠습니다.

도움이 되셨다면 광고 한번 클릭해주세요. 블로그 운영에 큰 힘이 됩니다. 감사합니다.

관련글 더보기

댓글 영역