通过编程导航 Vue.js 传递 props

问题描述 投票:0回答:4

我有一个 Vue 组件,它有一个名为“title”的 prop,例如:

<script>
export default {
  props: ['title'],
  data() {
    return {
    }
  }
}
</script>

在完成某个操作后,我以编程方式导航到该组件。 有没有办法以编程方式路由用户,同时设置 prop 值?我知道您可以创建这样的链接:

<router-link to="/foo" title="example title">link</router-link>

但是,有没有办法做类似以下的事情?

this.$router.push({ path: '/foo', title: 'test title' })

编辑:

按照建议,我已将路线更改为以下:

   {
      path: '/i/:imageID',
      component: Image,
      props: true
    }

导航至以下内容:

this.$router.push({ path: '/i/15', params: {title: 'test title' }})

但是,我的图像组件(模板 - 见下文)仍然没有显示任何标题。

<h1>{{ title}}</h1>

有什么可能导致问题吗?

javascript vue.js vuejs2 vue-router
4个回答
147
投票

使用参数。

this.$router.push({ name: 'foo', params: {title: 'test title' }})

注意:您必须指定

name
。如果您使用
this.$router.push
调用
path
,则此操作不起作用。

并设置路由接受参数作为 props。

{path: "/foo", name:"foo", component: FooComponent,  props: true}

props: true
记录在此处


19
投票

vue-router 文档明确指出

params
仅适用于
name
而不是
path

// set  props: true in your route definition
const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
// This will NOT work
router.push({ path: '/user', params: { userId }}) // -> /user

如果您使用

path
,请在路径本身中传递参数或使用
query
,如下所示:

router.push({ path: `/user/${userId}` }) // -> /user/123

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

3
投票

在 router 中定义的子路由也遇到同样的问题。下面的 router.js 显示了映射到名为

的子路由
<router-view name="create"></router-view>
<router-view name="dashboard"></router-view>

路由器.js

    {
      path: "/job",
      name: "Job",
      component: () => import("./views/JobPage"),
      children: [
        {
          path: "create",
          name: "JobCreate",
          components: {
            create: JobCreate
          }
        },
        {
          path: ":id",
          name: "JobConsole",
          components: {
            dashboard: JobConsole
          }
        }
      ]
    },

当我尝试从 create 传递 props 时,vue-router 无法捕获 JobConsole 所需的动态路由匹配:

      this.$router.push(
        {
          name: "Job",
          params: {
            id: this.ID_From_JobCreate
          }
      )


0
投票

有几乎相同的问题,我认为这些答案可能太旧了。从https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22阅读似乎没有办法做这样的事情:

this.$router.push({ name: 'foo', params: {title: 'test title' }})

或者不再。我最终使用了 Store.js,它快速且易于使用 https://www.npmjs.com/package/store-js

© www.soinside.com 2019 - 2024. All rights reserved.