首页 > 解决方案 > Vue JS 组件结构

问题描述

我正在学习 Vue,我怀疑我的 Vue 应用程序的结构。

我了解到组件可以包括逻辑和模板。然后我分离了我的组件,每个人都从主应用程序获取配置(config 是一个坐标为 config.ll、config.lng 的对象)。

我对我的搜索和发现 API 服务进行 ajax 调用,并在每个组件中显示结果(当前位置、您附近的场所等)。

我的问题是:将调用封装到每个组件中是否正确?还是在通用应用程序中获取所需数据,然后使用专业人员与组件共享结果更好?

我问这个问题是因为当我想将类别的点击传达给场所附近的组件时,困难的部分现在开始了,我尝试使用发射但没有成功。

//MAIN
<sidebar :config="config"></sidebar>
<content :config="config"></content>

//IN SIDEBAR
<currentLocation :config="config"></currentLocation>
<categories :config="config"></categories>

//IN CONTENT
<venueDetails :config="config"></venueDetails>
<venuesNearYou :config="config"></venuesNearYou>

标签: vue.jscomponentsemit

解决方案


我认为您可以使用类似事件总线的方法,我们在 vue 应用程序中进行了三种类型的通信(没有 vuex) - 父子之间的通信,这是由道具组成的完整字段 - 通过来自子级的自定义事件处理子级到父级的通信,由父级监听 -我们使用事件总线方法的非父子组件之间的通信父子示例 -

子到父示例 - 在子中 this.$emit('sendDataToParent',{someData:"some data"}}) - 在父中

主 vue 实例中的事件总线 const eventBus = new Vue()

在某些组件中从哪里发送数据 import eventBus eventBus.$emit('someEvent','some data')

在某些组件中从哪里接收数据

created() {
// register listener
  eventBus.$on('someEvent',()=>{

}) }

更多参考 https://vuejs.org/v2/guide/components.html#Passing-Data-to-Child-Components-with-Props https://vuejs.org/v2/guide/components.html#Emitting- a-Value-With-an-Event https://medium.com/easyread/vue-as-event-bus-life-is-happier-7a04fe5231e1


推荐阅读