programing

vue 라우터로 소품으로 오브젝트를 건네주는 방법

coolbiz 2022. 7. 7. 23:45
반응형

vue 라우터로 소품으로 오브젝트를 건네주는 방법

다음 바이올린 https://jsfiddle.net/91vLms06/1/을 사용하고 있습니다.

const CreateComponent = Vue.component('create', {
  props: ['user', 'otherProp'],
  template: '<div>User data: {{user}}; other prop: {{otherProp}}</div>'
});

const ListComponent = Vue.component('List', {
  template: '<div>Listing</div>'
});

const app = new Vue({
  el: '#app',
  router: new VueRouter(),
  created: function () {
    const self = this;
        // ajax request returning the user
    const userData = {'name': 'username'}

    self.$router.addRoutes([
      { path: '/create', name: 'create', component: CreateComponent, props: { user: userData }},
      { path: '/list', name: 'list', component: ListComponent },
      { path: '*', redirect: '/list'}
    ]);
    self.$router.push({name: 'create'}); // ok result: User data: { "name": "username" }; other prop:
    self.$router.push({name: 'list'}); // ok result: Listing

    // first attempt
    self.$router.push({name: 'create', props: {otherProp: {"a":"b"}}}) // not ok result: User data: { "name": "username" }; other prop:
    self.$router.push({name: 'list'}); // ok result: Listing

    // second attempt
    self.$router.push({name: 'create', params: {otherProp: {"a":"b"}}}) //not ok result: User data: { "name": "username" }; other prop:
  }
});

먼저 보시는 바와 같이 저는 앞으로 넘어갑니다.CreateComponentuser루트를 초기화할 때에요

나중에 다른 자산을 전달해야 합니다.otherProp그리고 여전히user파라미터를 지정합니다.이렇게 하려고 해도 보내는 개체가 컴포넌트에 전달되지 않습니다.

어떻게 패스하지?otherProp그리고 여전히user?

의 진정한 목적은otherProp폼에 데이터를 채우는 것입니다.목록 부분에 오브젝트가 있고 "편집" 버튼을 클릭했을 때 목록에 있는 데이터로 폼을 채우고 싶습니다.

소품 기능 모드와 기능 모드를 사용하여 조작할 수 있습니다.params

데모: https://jsfiddle.net/jacobgoh101/mo57f0ny/1/

경로를 추가할 때 기본 특성을 가지도록 소품의 기능 모드를 사용합니다.user그리고 그것은 추가될 것이다.route.params소품으로.

{
    path: '/create',
    name: 'create',
    component: CreateComponent,
    props: (route) => ({
        user: userData,
        ...route.params
    })
}

푸시 방식으로 전달된 패럴은 자동으로 소품에 추가됩니다.

self.$router.push({
    name: 'create',
    params: {
        otherProp: {
            "a": "b"
        }
    }
})

다음은 Router를 사용하여 객체를 전송하는 간단한 솔루션입니다.

this.$router.push({
 name: 'someName'
 params: {
  obj: {...someObject}
 },
});

그리고 다음 페이지에서 obj를 사용하고 싶다면.아래의 데이터를 얻을 수 있습니다.

this.$route.params.obj

언급URL : https://stackoverflow.com/questions/50506470/how-to-pass-an-object-as-props-with-vue-router

반응형