javascript - 在 vue 路由器中的两个组件之间传递 Prop

标签 javascript vue.js

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


组件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 它会起作用。

最佳答案

您的路由器属性位于您在组件 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 来解耦你的组件。

关于javascript - 在 vue 路由器中的两个组件之间传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54698980/

相关文章:

html - 如何根据链接是外部链接还是内部链接在Vue中动态呈现<router-link>或<a>?

vue.js - 来自 swagger 规范的 vue.js 客户端

vue.js - 使用Vuejs进行渐进增强——解析已有的HTML

javascript - 在 JavaScript 中从 Base64 字符串创建 BLOB

javascript - Angular 绑定(bind)在 Chrome/Opera 中不起作用

javascript - 如何在 openlayers3 中更改图像颜色?

javascript - 使用 Vue 增加格式化计时器

javascript - S3 从浏览器上传带有预签名 url 的图像

javascript - 如何在 JQuery TE 工具栏中只配置我需要的选项?

javascript - Vue.js 中可编辑文本区域的 TreeView