【问题标题】:Vue 3 - get access to parentVue 3 - 访问父级
【发布时间】:2023-01-17 18:42:47
【问题描述】:

我正在将 Vue 2 迁移到 Vue 3。 我正在使用 ag-grid 并在每一行中使用按钮,这些按钮使用父组件的方法。 在 Vue 2 中,语法很简单:this.$parent.$parent(由于 Ag-Grid,我使用了两次 $parent) 但现在我面对的是 Vue 3,我想让相同的组件工作,但不知道如何编写它。

我很高兴能提供帮助

这是我实际执行此操作的代码:

<template>
  <div class="main">
    <i class="fa fa-info icons" @click="infoButton"></i>
    <i class="fa fa-file icons" @click="filesHistoryButton"></i>
    <i class="fa fa-edit icons" @click="editReminderButton"></i>
  </div>
</template>

<script>
import defineComponent from "vue";
import { getCurrentInstance } from "vue";
export default defineComponent({
  name: "Actions",
  setup(){
    const instace = getCurrentInstance();
    
    console.log(instace.parent.parent)
  },
  data() {
    return {};
  },
  computed: {},
  beforeMount() {},
  mounted() {},
  methods: {
    infoButton() {
      this.$parent.$parent.GetNotificationHistory(this.params.data.id);
    },
    filesHistoryButton() {
      this.$parent.$parent.GetFilesLists(this.params.data.id);
    },
    editReminderButton() {
      this.$parent.$parent.EditReminder(this.params.data.id);
    }
  }
});
</script>

【问题讨论】:

  • 预计在Vue 3中也是如此。是关于composition api的吗?那么问题就问错了,因为在V2中可以使用composition api,而在V3中可以使用options api。我希望它能与 instance.proxy.$parent.$parent 的组合 api 一起工作。 $parent 的使用是一个非常糟糕的做法,您可以考虑将其重构为更好的设计

标签: javascript vue.js vuejs3


【解决方案1】:

$parent 属性应该与 Vue 3 ether 一起使用。

请确保您没有在父组件中使用 expose 声明,这会限制您的方法的可访问性。

正如 Estus Flask 已经说过的,这不是推荐的做法,因为它会在您的组件之间产生紧密的耦合。

使用自定义事件与父组件交互会好很多。
请参阅有关 Component Events 的 Vue 文档

像这样:

export default defineComponent({
  name: "Actions",
  emits: ['infoButton','filesHistoryButton','editReminderButton'], // <--- define events
  setup(){
    const instace = getCurrentInstance();
    
    console.log(instace.parent.parent)
  },
  data() {
    return {};
  },
  computed: {},
  beforeMount() {},
  mounted() {},
  methods: {
    infoButton() {
      this.$parent.$parent.GetNotificationHistory(this.params.data.id);
      this.$emit('infoButton', this.params.data.id);
    },
    filesHistoryButton() {
      this.$parent.$parent.GetFilesLists(this.params.data.id);
      this.$emit('filesHistoryButton', this.params.data.id);

    },
    editReminderButton() {
      this.$parent.$parent.EditReminder(this.params.data.id);
      this.$emit('editReminderButton', this.params.data.id);
    }
  }
});

并相应地在父组件中:

@info-button="GetNotificationHistory"

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2021-07-20
    • 2021-02-20
    • 1970-01-01
    • 2015-12-01
    • 2021-08-13
    相关资源
    最近更新 更多