代码之家  ›  专栏  ›  技术社区  ›  tzortzik

如何使用vue路由器将对象作为道具传递?

  •  33
  • tzortzik  · 技术社区  · 7 年前

    我有下面的小提琴 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:
      }
    });
    

    正如你首先看到的,我要传递给 CreateComponent 这个 user 就在我初始化路线的时候。

    稍后我需要通过另一个属性 otherProp 并且仍然保持 使用者 参数当我尝试这样做时,我发送的对象不会传递给组件。

    我怎样才能通过考试 其他支柱 并且仍然保持 使用者 ?

    这项计划的真正目的 其他支柱 就是用表格中的数据填写表格。在列表部分,我有一个对象,当我点击“编辑”按钮时,我想用列表中的数据填充表单。

    2 回复  |  直到 5 年前
        1
  •  0
  •   YOUNG MIN CHO    4 年前

    它可以通过使用 props's Function mode 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"
            }
        }
    })
    
    推荐文章