首页 文章

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

提问于
浏览
11

我有一个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' }})

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

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

有什么可能导致问题吗?

2 回答

  • 23

    使用参数 .

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

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

    并设置接受params作为道具的路线 .

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

    props: truedocumented here .

  • 2

    vue-router docs明确表示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
    

    如果您使用路径,请在路径中传递params或使用查询,如下所示:

    router.push({ path: `/user/${userId}` }) // -> /user/123
    
    // with query, resulting in /register?plan=private
    router.push({ path: 'register', query: { plan: 'private' }})
    

相关问题