【发布时间】:2021-10-29 03:55:12
【问题描述】:
我正在尝试使用 Typescript 将以下代码表单选项转换为 Vue 中的组合 API。
data() {
return {
items: [
'Car',
'Truck',
'Bike',
'Caravan'
],
activeItem: 0,
show: false,
};
},
methods: {
showDropdown() {
this.show = !this.show;
},
setActiveItem(item) {
this.activeItem = this.items.indexOf(item);
this.show = false;
}
},
computed: {
dropdownItems() {
return this.items.filter((item,i) => i !== this.activeItem)
}
}
这就是我所拥有的。我还是 Vue 和 Typescript 的新手,所以我使用这个例子来了解更多关于组合 API 和 Typescript 的信息。
setup() {
const activeItem = 0;
const show = ref(false);
const items = ref([
'Car',
'Truck',
'Bike',
'Caravan'
]);
function showDropdown(this: any) {
this.show = !this.show;
}
function setActiveItem(this: any, item: string) {
this.activeItem = this.items.indexOf(item);
this.show = false;
}
const dropdownItems = computed(function (this: any, item: string) {
return this.items.filter((item, i) => i !== this.activeItem);
});
return {
activeItem,
show,
items,
showDropdown,
setActiveItem,
dropdownItems,
};
},
我遇到的错误例如在setActiveItem 方法中是'this' implicitly has type 'any' because it does not have a type annotation. 所以当我通过this: any 参数时它可以工作,但我不知道这是否是正确的方法?
第二个问题是我无法让计算方法工作我不知道如何正确实现它。有人可以帮我解决这个问题吗?
【问题讨论】:
标签: javascript vue.js vue-component vue-composition-api