vue.js - 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 的组件的数据部分中获取对组件方法的引用?
解决方案
推荐阅读
- ios - 如何创建一个在多个 ViewController 上保持相同的标题层?
- java - Java 内存模型 - 令人惊讶的行为
- javascript - Discord bot 'connect' 命令与 discordjs v13、@discordjs/voice 和 SlashCommandBuilder
- python - 在python中使用xslt转换xml
- reactjs - 当我点击 li 标签时,路由不起作用我的 url 没有改变
- css - 在 Safari 上显示菜单的 CSS 媒体查询问题
- c - `cond_broadcast` 是如何工作的?
- r - R 带有 javascript 渲染的可反应条件可扩展行
- c - C动态数组在通过函数时有未知值吗?
- flutter - 使用现有字符串或整数生成整数?