简体   繁体   English

Vue.js:如何触发从一个组件到另一个组件的方法

[英]Vue.js : howto trigger method from one component to another

Vue.js Version 2.6.11 incorporated into asp.net core mvc views. Vue.js 版本 2.6.11 并入 asp.net 核心 mvc 视图。

Imagine the following scenario.想象以下场景。 A page has 2 components on it.一个页面上有 2 个组件。

<v-masterlist v-bind:dummy-prop="dummyProp"> </v-masterlist>
<v-detail v-bind:itemid="itemId"></v-detail>

The masterlist retrieves a list of items from on api upon creating. masterlist 在创建时从 api 上检索项目列表。 When an item gets selected, the component emits an event captured by the page.当一个项目被选中时,组件会发出一个由页面捕获的事件。 That updates itemId, triggering the detail component to retrieve the full record from the api.这会更新 itemId,触发详细信息组件从 api 检索完整记录。

In the detail component, users can update or delete that record.在详细信息组件中,用户可以更新或删除该记录。 Those action should trigger masterlist to again retrieve the updated list of items from the api.这些操作应触发 masterlist 再次从 api 检索更新的项目列表。

I set this now up by having a dummy prop on masterlist.我现在通过在 masterlist 上设置一个虚拟道具来设置它。 Whenever that property changes, the list is retrieved from the api.只要该属性发生更改,就会从 api 检索列表。

Upon update/delete in the detail component an event is emitted explaining what action (update/delete) was performed.在详细信息组件中更新/删除时,会发出一个事件,解释执行了哪些操作(更新/删除)。 That event is captured in the page, setting dummyProp to a new random value, hence triggering masterlist to update itself.该事件在页面中被捕获,将 dummyProp 设置为一个新的随机值,从而触发 masterlist 进行自我更新。

It works fine, but seems messy.它工作正常,但看起来很乱。 It would be better if masterlist would be capturing events emitted by detail.如果 masterlist 能够捕获细节发出的事件会更好。 Is that possible?那可能吗? Or any other suggestions?或者有什么其他建议?

At the end we started using this emitter component, works fine.最后我们开始使用这个发射器组件,工作正常。 https://github.com/developit/mitt https://github.com/developit/mitt

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

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