繁体   English   中英

如何在不使用 vuex 的情况下将对象从 A 组件传递到 Vue.js 中的 B 组件?

[英]How can I pass an Object from A component to B component in Vue.js without using vuex?

这两个组件是在 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.vue发送到B 组件

代码如下:

 //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 component的对象。

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

在子组件中使用this.$emit('event_name', some_data)并在父组件的模板中捕获,例如<child-component v-on:event_name="methodName">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM