Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js 如何使用Vue路由器将道具传递给子组件?_Vue.js_Vue Router - Fatal编程技术网

Vue.js 如何使用Vue路由器将道具传递给子组件?

Vue.js 如何使用Vue路由器将道具传递给子组件?,vue.js,vue-router,Vue.js,Vue Router,我有一个带有导航和布局的Vue组件,它使用总线与子组件通信。总线作为道具传递给子组件,然后子组件使用$emit export default class Dashboard extends Vue { protected bus: Vue = new Vue(); mounted() { if (this.bus != null) { this.bus.$on("save", () => { // }); } } }

我有一个带有导航和布局的Vue组件,它使用总线与子组件通信。总线作为道具传递给子组件,然后子组件使用$emit

export default class Dashboard extends Vue {

  protected bus: Vue = new Vue();

  mounted() {
    if (this.bus != null) {
      this.bus.$on("save", () => {
        //
      });
    }
  }
}

@Component({ props: ["bus"] })
export default class Child extends Vue {
   protected bus!: Vue;

   save() {
      this.bus.$emit("save");
   }  
}
这在标准情况下工作正常


在Vue路由器的情况下,如何将总线组件从父节点注入子节点

您应该在一个单独的文件中创建一个总线实例,您可以将该实例导入到需要使用它的任何其他文件中,该实例将在导入它的所有位置保持不变

您可以使用
data()
对象,而不是作为道具传递,因为它将充当全局存储,但这就是它的用途

//BusDepot.js
从“Vue”导入Vue
导出常量仪表板总线=新Vue({
数据:{
mySharedValue:“它是全球性的!”
}
})
从'BusDepot'导入{DashboardBus}
导出默认类仪表板扩展Vue{
创建(){
仪表板总线。$on('save',()=>{
console.log(DashboardBus.mySharedValue)
});
}
}
从'BusDepot'导入{DashboardBus}
导出默认类子级扩展Vue{
保存(){
仪表板总线。$emit('save');
}  
}

如果使用作为中央数据存储来解决道具传递问题,则可以使用主Vue实例作为事件总线:

从'BusDepot'导入{DashboardBus}
导出默认类仪表板扩展Vue{
创建(){
const vm=this
vm.$root.$on('dashbaord.save',()=>{
console.log(vm.store.state.mySharedValue)
});
}
}
从'BusDepot'导入{DashboardBus}
导出默认类子级扩展Vue{
保存(){
这是.$root.$emit('dashbaord.save');
}  
}

路由器的参数只是键值对,我认为不可能在那里传递对象引用…关于如何将引用传递给子对象的其他想法?将其作为属性传递给组件,或在根上用前缀事件和路由道具传递它。类似于
this.$emit(`${this.$route.params.prefix}:save`)
。通常事件总线不会这样传递。为什么不使用全局事件总线?此外,中央管理层简化了组件通信,您可以考虑使用VUEX。在Vuex中保存对象,并将其加载到任何路由上。也可以传递对象参数,但这可能是一种反模式。我使用Vuex作为应用程序状态,但例如,父级应该协调显示子组件的错误消息,但在Vuex中使用它感觉不正确。或者,如果子组件出现错误,则父组件应淡出。或者,父级可能需要基于一个子组件更改其他子组件。使用Vuex进行这种交流感觉不像Vue。我更喜欢使用$emit-just-to-child组件而不是子组件来实现Vue。我将乘环球巴士去。