-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathindex.vue
92 lines (85 loc) · 2.1 KB
/
index.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<template>
<div id="app">
<div v-if="data">
<h3>Page {{ page }}</h3>
<ul>
<li v-for="article in data.data">
<a :href="article.url">{{ article.title }}</a>
</li>
</ul>
<div v-if="isValidating">
loading...
</div>
<nuxt-link :to="`/?page=${page - 1}`" v-if="page > 1">
Previous page
</nuxt-link>
<nuxt-link :to="`/?page=${page + 1}`">Next page</nuxt-link>
</div>
</div>
</template>
<script lang="ts">
import useSWRV, { IConfig } from '../../../esm'
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
import {
ref,
computed,
Ref,
watch,
defineComponent
} from '@vue/composition-api'
type RequestKey = (() => AxiosRequestConfig) | AxiosRequestConfig
function useRequest<Data = unknown, Error = unknown> (
request: Ref<RequestKey>,
config?: IConfig
) {
return useSWRV<AxiosResponse<Data>, AxiosError<Error>>(
() => JSON.stringify(request.value),
key => axios(JSON.parse(key)),
config
)
}
export default defineComponent({
name: 'App',
setup (props, context) {
const page = ref(1)
watch(
() => context.root.$route.query.page,
queryPage => {
page.value = parseNumberQueryParam(queryPage, 1)
}
)
const request = computed(() => {
const requestConfig: AxiosRequestConfig = {
method: 'get',
url: `https://dev.to/api/articles?tag=nuxt&state=rising&page=${page.value}`
}
return requestConfig
})
const { data, isValidating } = useRequest<Post[]>(request)
function nextPage () {
page.value += 1
}
return { data, nextPage, page, isValidating }
}
})
type QueryParam = string | (string | null)[]
function parseNumberQueryParam (
param: QueryParam | undefined,
defaultValue: number
): number {
if (!param) return defaultValue
const p = Array.isArray(param) ? param[0] : param
if (p) {
const int = parseInt(p)
if (isFinite(int)) return int
}
return defaultValue
}
type Post = {
type_of: string
id: number
title: string
description: string
url: string
}
</script>