【问题标题】:Vuejs: Access a Parent Component Method from Child ComponentVuejs:从子组件访问父组件方法
【发布时间】:2022-01-19 17:54:52
【问题描述】:

我无法从子组件访问父方法。我按照official document 所说的做了。

父模板:

<template>
  <v-app>
    <v-sheet height="100vh">
      <v-sheet height="100vh" class="overflow-y-auto">
        <div ref="ComponentDisplay" :is="currentComponent"></div>
      </v-sheet>
      <DrawerComponent></DrawerComponent>
    </v-sheet>
  </v-app>
</template>

<script>
export default {
  name: 'Dashboard',
  data: function () {
    return {
      currentComponent: null
    }
  },
  methods: {
    displayComponent (component) {
      this.currentComponent = component
    }
  }
}
</script>

抽屉组件:

export default {
  name: 'DrawerComponent',
  methods: {
    exit: function () {
      logout()
    },
    swapComponent: function (component) {
      this.$parent.displayComponent(this.components[component])
    }
  },
  data: () => ({
    drawer: false,
    group: null,
    mini: true,
    components: {}
  }),
  watch: {
    group () {
      this.drawer = false
    }
  }
}
</script>

在线:

this.$parent.displayComponent(this.components[component])

出现以下错误:

TypeError: this.$parent.displayComponent 不是函数

【问题讨论】:

  • 你误解了 Vue 组件通信模型。组件通过 props 获取数据,并仅通过事件与外界通信。组件的整个思想就是封装,即组件除了自身之外什么都不知道。
  • @connexo,是的,我刚开始使用Vue,很多东西都不知道。

标签: vue.js


【解决方案1】:

使用$parent 不是一个好习惯,但您可以使用emit 从子组件发送事件以在父组件中运行某些方法:

在子组件中使用您的有效负载发出事件:

    swapComponent: function (component) {
      this.$emit("swap-component",this.components[component])
    }

在父母一中:


 <DrawerComponent @swap-component="displayComponent"></DrawerComponent>

并将div 更改为component


<div ref="ComponentDisplay" :is="currentComponent"></div>

【讨论】:

  • 错误消失了,但引发了其他问题。 [Vue warn]: Error in nextTick: "TypeError: Cannot read properties of null (reading 'componentInstance')" TypeError: Cannot read properties of null (reading 'componentInstance')
  • 试试&lt;component ref="ComponentDisplay" :is="currentComponent??'div'"&gt;&lt;/component&gt; 而不是&lt;div ref="ComponentDisplay" :is="currentComponent"&gt;&lt;/div&gt;
  • 我修好了,我只是全局注册了组件而不是本地组件。
  • 如果你使用 Vue 3?您可以从子项中的父项中注入任何方法并在任何地方调用它。 (组合 API 更好)
  • 该逻辑对组合 API 也有效,只需使用来自 setup(props,{emit})emit 而不是 this.$emit
猜你喜欢
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 2020-07-29
  • 2017-01-07
  • 2020-09-16
相关资源
最近更新 更多