Reputation: 1154
I am trying to convert the following code form options
to composition
API in Vue using Typescript.
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)
}
}
This is what I have. I am still new to Vue and Typescript so i am using this example to learn more about composition API and 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,
};
},
The errors I am getting are for example in the setActiveItem
method is 'this' implicitly has type 'any' because it does not have a type annotation.
So when I pass this: any
params it works but I don't know if this is the right way to do it?
Second problem is I can't get the computed method to work I don't know how to implement it correctly. Is there someone who can help me out with this?
Upvotes: 0
Views: 916
Reputation: 23480
Computed method you just import import { ref, computed } from "@vue/reactivity";
. With ref
you need to use value
. (Following code is without typescript)
import { ref, computed } from "@vue/reactivity";
setup() {
const activeItem = ref(0);
const show = ref(false);
const items = ref([
'Car',
'Truck',
'Bike',
'Caravan'
]);
const dropdownItems = computed(() => items.value.filter((item, i) => i !== activeItem.value));
const showDropdown = () => {
show.value = !show.value;
}
const setActiveItem = (item) => {
activeItem.value = items.value.indexOf(item);
show.value = false;
}
return {
activeItem,
show,
items,
showDropdown,
setActiveItem,
dropdownItems,
};
},
Upvotes: 1
Reputation: 222309
The objective of composition API is to get rid of dynamic this
that isn't an instance of a specific class but an object that aggregates properties from component definition and puts limitations on TypeScript typing.
Instead, variables defined in the scope of setup
are supposed to be accessed directly:
const dropdownItems = computed((item: string) => {
return unref(items).filter((item, i) => i !== unref(activeItem));
});
activeItem
is supposed to be a ref as well.
Upvotes: 1