【问题标题】:How can I pass an Object from A component to B component in Vue.js without using vuex?如何在不使用 vuex 的情况下将对象从 A 组件传递到 Vue.js 中的 B 组件?
【发布时间】:2018-04-23 07:32:57
【问题描述】:

这两个组件在 app.vue 中使用 vue-router 定义如下:

<div class='app'>
    <div class='nav'>
        <router-link to='/a'>to A component</router-link>
        <router-link to='/b'>to B component</router-link>
    </div>
    <div class='content'>
        <router-view></router-view>
    </div>    
</div>  

我试图接收一个包含 app.vue 中的对象的事件,该对象是来自 A 组件 的 $emit,然后我可以从 发送该对象app.vueB 组件

代码如下:

    //script in A component
    data () {
       toModify (good) {
         console.log(good)  // {'name': 'mike'}
         this.$emit('tomodify', [good])
       }
    }
    <!-- A component -->
    <button class="modifyBtn" @click="toModify(good)">Modify</button>

      //script in app.vue
        methods: {
          sendData (good) {
            this.agood = good
            console.log(this.agood)  // undefined
          }
        }
      <!--app.vue-->
      <div class="view-wrapper">
        <router-view @tomodify="sendData(good)"></router-view>
      </div>

而且我不知道为什么在 app.vue 中我可以获取事件但没有来自 A 组件 的对象。

【问题讨论】:

  • 传递一个props给parent,parent传递props给child
  • @pirs 将道具传递给父母?如何?我试过 $emit 但它不起作用。
  • 老实说,使用 Vuex,了解概念,不要再浪费时间了。

标签: javascript vue.js vue-component vue-router


【解决方案1】:

从父组件向子组件传递数据的官方方法是使用props。将数据从子组件传递到其父组件的官方方法是使用emit

事件在子组件中使用this.$emit('event_name', some_data) 发出,并在父组件的模板中捕获,例如&lt;child-component v-on:event_name="methodName"&gt;

【讨论】:

  • 是的,我的回答没有提供完整的解决方案,但它包含从父母到孩子以及从孩子到父母的传递信息。两者的结合是实现预期目标所需要的——即首先使用emit,然后通过props 传播更改。我还特别添加了一个 emit 示例,因为我注意到一条评论询问如何让它工作。
  • 是的,这是一个很好的答案,但不是一个好习惯,除了一两个道具.. 非常罕见
  • 但是如果子组件 $emit 来自 而不是 怎么办?
  • 对于您的router-view 组件,您是否尝试过@tomodify="sendData"
  • 我想我可能理解这个问题。看起来您正试图在两个单独的同级组件中捕获相同的 emit。但这是不可能的。 emit 只能在创建emit 的孩子的范围内使用。如果您想将数据发送到router-view,则应改为使用props 并以这种方式传递数据。
猜你喜欢
  • 2021-10-02
  • 2019-02-06
  • 2021-04-08
  • 2018-07-11
  • 2017-09-04
  • 2018-03-29
  • 2013-08-23
  • 2019-07-30
  • 2019-03-30
相关资源
最近更新 更多