如何使用 vue 路由器将对象作为道具传递? [英] How to pass an object as props with vue router?

查看:25
本文介绍了如何使用 vue 路由器将对象作为道具传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下小提琴 https://jsfiddle.net/91vLms06/1/

I have the following fiddle 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:
  }
});

正如您首先看到的,我在初始化路由时将 user 传递给 CreateComponent.

As you can see first I am passing to CreateComponent the user just when I initialize the route.

稍后我需要传递另一个属性 otherProp 并且仍然保留 user 参数.当我尝试这样做时,我发送的对象没有传递给组件.

Later I need to pass another property otherProp and still keep the user parameter. When I try to do this the object I send is not passed to the component.

如何传递otherProp 并保留user?

otherProp 的真正目的是用表单中的数据填充表单.在列表部分我有对象,当我点击编辑"按钮时,我想用来自列表的数据填充表单.

The real purpose of the otherProp is to fill a form with the data from it. In the listing part I have the object and when I click the "edit" button I want to populate the form with the data that comes from the listing.

推荐答案

可以使用 props 的函数模式params

演示:https://jsfiddle.net/jacobgoh101/mo57f0ny/1/

添加路由时,使用props的Function模式,这样它就有默认属性 user 它将添加 route.params 作为道具.

when adding routes, use props's Function mode so that it has a default property user and it will add route.params as props.

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

push 中传入的参数会自动添加到 props 中.

params passed in push will automatically be added to props.

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

这篇关于如何使用 vue 路由器将对象作为道具传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆