我正在将 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>
$parent
属性应该与 Vue 3 ether 一起使用。
确保不在父组件中使用 expose 声明,这会限制方法的可访问性。
就像 Estus Flask 已经说过的那样,这不是推荐的做法,因为它会在组件之间造成紧密耦合。
使用自定义事件与父组件交互会好得多。
请参阅有关 组件事件
像这样:
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"
对于带有
<script setup>
的 vue3,你不能这样做 this
,
并且也无法使用选项 api(即通过 defineComponent
)
<script>
defineComponent({
...,
setup() {
const myRef = this.$parent.$refs.myRef;
},
...,
});
</script>
可以用以下代码代替:
<script>
const self = getCurrentInstance();
const myRef = self.parent.refs.myRef;
</script>