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

Vue路由器将对象作为属性传递

  •  11
  • tzortzik  · 技术社区  · 8 年前

    我有下列小提琴 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 second
        self.$router.push({name: 'create', params: {otherProp: {"a":"b"}}}) //not ok result: User data: { "name": "username" }; other prop:
      }
    });
    

    正如你首先看到的,我正经过 CreateComponent 这个 user 就在我初始化路由的时候。

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

    我怎么通过 其他道具 仍然保持 用户 ?

    的真正目的 其他道具 是用表单中的数据填充表单。在列表部分,我有一个对象,当我单击编辑按钮时,我想用来自列表的数据填充表单。

    1 回复  |  直到 8 年前
        1
  •  12
  •   Jacob Goh    8 年前

    它可以通过使用 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
        })
    }
    

    在push中传递的参数将自动添加到props中。

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