Skip to content

Commit 6166ede

Browse files
committed
Typing ref's examples
1 parent ce4175b commit 6166ede

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

vue-3.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,46 @@ declare const props: {
3030
3131
export const welcome = computed(() => `Welcome, ${props.name}!`)
3232
```
33+
34+
## Composition API
35+
36+
### Refs
37+
38+
Vue can infer the type of your `ref`'s but if you need to represent some more complex types you can do so with generics:
39+
40+
```ts
41+
import {ref} from "vue"
42+
43+
interface PersonInfo {
44+
firstName: string,
45+
surname: string,
46+
age: number
47+
}
48+
49+
const people = ref<PersonInfo[]>([])
50+
51+
```
52+
53+
Alternatively you can use casting with `as`. This should be used if the type is unknown. Consider this example where we create a composition wrapper function around `fetch` and we dont know the data structure that will be returned.
54+
55+
```ts
56+
57+
import { ref, Ref } from "vue";
58+
59+
type ApiRequest = () => Promise<void>;
60+
61+
// When using this function we can supply the type via generics
62+
export function useAPI<T>(url: RequestInfo, options?: RequestInit) {
63+
64+
const response = ref() as Ref<T>; // 👈 note we're typing our ref using `as`
65+
66+
const request: ApiRequest = async () => {
67+
const resp = await fetch(url, options);
68+
const data = await resp.json();
69+
response.value = data;
70+
};
71+
72+
return { response, request };
73+
}
74+
75+
```

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy