首页 > 解决方案 > Vue2 - 如何在基于 Composition-Api 的组件的数据部分中获取对组件方法的引用?

问题描述

我正在将 Vuejs2 项目中的 TypeScript“基于类的 Vue 组件”迁移到“基于 Composition-Api 的组件”。

在我在“数据”部分中使用的组件中,引用了同一组件的方法。

在基于类的组件中,它看起来像这样(效果很好):

<template>
    <section class="my-dynamic-form">
        <!-- render the form -->
        <!-- ... -->
        <div v-for="formRow in formRows">
            <!-- ... -->
            <button
                v-if=" formRow.type === 'ACTION_BUTTON'"
                @click="formRow.action">
                {{ formRow.text }}
            </button>
        </div>
    </section>
</template>


<script lang="ts">

import Vue from "vue";

export default class MyFormComponent extends Vue {

    public formRows: Array<any> = [
        // ...
        {
            type: "ACTION_BUTTON",
            text: 'Save',
            action: this.update, // <--- works
        }
    ];

    update() {
        alert("update data on server...");
    }
}

</script>

将其更改为“基于组合 Api 的组件”后,我遇到的问题是不再识别对方法“更新”的引用..给出错误“TS2339:“Vue”类型上不存在属性“更新”” . 这是代码:

<template>
    <section class="my-dynamic-form">
        <!-- render the form -->
        <!-- ... -->
        <div v-for="formRow in formRows">
            <!-- ... -->
            <button
                v-if=" formRow.type === 'ACTION_BUTTON'"
                @click="formRow.action">
                {{ formRow.text }}
            </button>
        </div>
    </section>
</template>


<script lang="ts">

import {defineComponent} from '@vue/composition-api'

export default defineComponent({
    data() {
        return {
            // ...
            formRows: [
                // ...
                {
                    type: "ACTION_BUTTON",
                    text: 'Save',
                    action: this.update, // <--- error - TS2339: Property 'update' does not exist on type 'Vue'
                }
            ]
        }
    },
    methods: {
        update() {
            alert("update data on server...");
        },
    },
});

</script>

我的问题是:如何在基于 Composition-Api 的组件的数据部分中获取对组件方法的引用?

标签: vue.jsvuejs2vue-composition-api

解决方案


推荐阅读