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

Ash*_*y B 25 javascript vue.js vue-router vuejs2

我有一个Vue组件,其中有一个名为'title'的道具,例如:

<script>
export default {
  props: ['title'],
  data() {
    return {
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

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

<router-link to="/foo" title="example title">link</router-link>
Run Code Online (Sandbox Code Playgroud)

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

this.$router.push({ path: '/foo', title: 'test title' })
Run Code Online (Sandbox Code Playgroud)

编辑:

如我所知,我已将路线更改为以下内容:

   {
      path: '/i/:imageID',
      component: Image,
      props: true
    }
Run Code Online (Sandbox Code Playgroud)

并导航到以下内容:

this.$router.push({ path: '/i/15', params: {title: 'test title' }})
Run Code Online (Sandbox Code Playgroud)

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

<h1>{{ title}}</h1>
Run Code Online (Sandbox Code Playgroud)

有什么可能导致问题吗?

Ber*_*ert 57

使用参数.

this.$router.push({ name: 'foo', params: {title: 'test title' }})
Run Code Online (Sandbox Code Playgroud)

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

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

{path: "/foo", name:"foo", component: FooComponent,  props: true}
Run Code Online (Sandbox Code Playgroud)

props: true记录在这里.

  • @AshleyB这最终按名称工作,但不是路径.我没有解释为什么不通过路径,但他们肯定在文档中按名称进行.https://codepen.io/Kradek/pen/eRapoZ?editors=1010 (3认同)
  • 确认它仍然通过名称而不是路径起作用: router.push({name: 'routeName', params: {whatever: 'andEver'}}) (2认同)

Ste*_*gin 6

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
Run Code Online (Sandbox Code Playgroud)

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

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

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