使用编程导航 Vue.js 传递道具

新手上路,请多包涵

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

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

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

 <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>

有什么可能导致问题吗?

原文由 Ash 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 304
2 个回答

使用参数。

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

注意:您必须指定 name 。如果您使用 path 调用 this.$router.push 这将不起作用。

并设置接受参数作为道具的路线。

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

props: true 记录在这里

原文由 Bert 发布,翻译遵循 CC BY-SA 3.0 许可协议

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' }})

原文由 Steven Spungin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题