javascript - 如何使用 vue 路由器将对象作为 Prop 传递?

标签 javascript vue.js vuejs2 vue-router

我有以下 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

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

如何传递 otherProp 并仍然保留 user

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

最佳答案

它可以通过使用 props's Function mode 来工作和参数

Vue 2 演示:https://jsfiddle.net/hacg6ody/

添加路由时,使用props's Function mode这样它就有一个默认属性 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"
        }
    }
})

关于javascript - 如何使用 vue 路由器将对象作为 Prop 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506470/

相关文章:

javascript - 我们如何为使用YOLO检测到的不同对象设置不同的 `colors`

vue.js - 从 axios 响应向 v-text-field 添加数据

vue.js - 如何将 vue-cli 与同一项目中现有的不相关的 webpack 设置集成?

javascript - 如何在不刷新vue.js的情况下更新页面上的数据?

javascript - JQuery 验证器 : error checking and message management

javascript - 使用 openstreetmap api 转换城市坐标

javascript - 使用 Web SDK 找出在 Firebase 数据库上被监视的路径

javascript - 从导入的文件访问 vue

javascript - Vue.js 2 - v-for 列表转发器中的计算属性

javascript - 对于文本输入,如何使点击它会选择所有内容?