【问题标题】:Pass props between two components in vue router在Vue路由器中的两个组件之间传递道具
【发布时间】:2019-07-08 23:40:06
【问题描述】:

我知道有很多问题可以回答我的问题,但我无法让其中一个运行。我想使用 vue 路由器将字符串从组件 A 传递到组件 B。在下面的示例中,如何在组件 B 中输出组件 A 的“名称”值。


组件A模板:

<form >
<input placeholder="type your name" v-model="name">
<button v-on:click="sayHello" type="submit" >Submit</button>

    <script>
sayHello() {
     this.$router.push({ name: 'ComponentB', params: {
        name: '{this.name}'}, props:true });
    }
</script>

组件 B:

<template>
<div class="container">
    <h1> Hello {{$route.params.name}}!</h1>
      </div>

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

路由器

{
  path: '/ComponentB',
  name: "CompB",
  component: CompB,
  props: true
}

仍然不知道如何在不使用 url 参数的情况下实现这一目标。 如果我将 CompB 的路径更改为 ComponentsB/:name 它就可以了。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您的路由器属性位于您在组件 A 中声明的 this.$route

    所以在你的情况下:

    组件 A:

    <script>
    sayHello() {
         this.$router.push({ name: 'ComponentB', query: {
            name: this.name }, props:true });
        }
    </script>
    

    组件 B:

    <template>
     <div class="container">
        <h1> Hello {{ $route.query.name }}!</h1>
     </div>
    </template>
    

    我建议阅读 https://router.vuejs.org/guide/essentials/passing-props.html 以使用 props 解耦您的组件。

    【讨论】:

    • 感谢您的回复。但这仍然不适用于我的情况。还有其他想法吗?
    • sayHello 函数,尝试在 $router.push 中引用“this.name”而不是“'{name}'”
    • 尝试使用“查询”而不是“参数”将数据传递给组件 B。我已更新响应以反映这一点
    • 没有改进。我也没有错误,我只是看到“你好!”
    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 2020-04-03
    • 2021-09-11
    • 2019-03-23
    • 2019-08-15
    • 2020-01-05
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多