feat: add vue router implement homepage

This commit is contained in:
mutoe 2020-10-01 13:36:11 +08:00
parent a789b6c9c6
commit f87360f09c
14 changed files with 251 additions and 79 deletions

5
.env
View File

@ -1,3 +1,2 @@
BASE_URL = /
API_HOST = https://conduit.productionready.io
BASE_URL=/
VITE_API_HOST=https://conduit.productionready.io

View File

@ -1,11 +1,11 @@
<template>
<img
alt="Vue logo"
src="./assets/logo.png"
>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
<RouterView></RouterView>
</template>
<script lang="ts" setup>
export { default as HelloWorld } from './components/HelloWorld.vue'
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'App',
})
</script>

View File

@ -1,17 +0,0 @@
<template>
<h1>{{ props.msg }}</h1>
<button @click="count++">
count is: {{ count }}
</button>
<p>Edit <code>components/HelloWorld.vue</code> to test hot module replacement.</p>
</template>
<script lang="ts" setup="props">
import { ref } from 'vue'
declare const props: {
msg: string
}
export const count = ref(0)
</script>

View File

@ -1,8 +0,0 @@
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}

View File

@ -1,6 +1,7 @@
import router from './routes'
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
// @ts-ignore
createApp(App).mount('#app')
createApp(App)
.use(router)
.mount('#app')

123
src/pages/Home.vue Normal file
View File

@ -0,0 +1,123 @@
<template>
<div class="home-page">
<div class="banner">
<div class="container">
<h1 class="logo-font">
conduit
</h1>
<p>A place to share your knowledge.</p>
</div>
</div>
<div class="container page">
<div class="row">
<div class="col-md-9">
<div class="feed-toggle">
<ul class="nav nav-pills outline-active">
<li class="nav-item">
<a
class="nav-link disabled"
href=""
>Your Feed</a>
</li>
<li class="nav-item">
<a
class="nav-link active"
href=""
>Global Feed</a>
</li>
</ul>
</div>
<div
v-for="article in articles"
:key="article.slug"
class="article-preview"
>
<div class="article-meta">
<a href="profile.html"><img src="http://i.imgur.com/Qr71crq.jpg"></a>
<div class="info">
<a
href=""
class="author"
>{{ article.author.username }}</a>
<span class="date">{{ new Date(article.createdAt).toDateString() }}</span>
</div>
<button class="btn btn-outline-primary btn-sm pull-xs-right">
<i class="ion-heart" /> {{ article.favoritesCount }}
</button>
</div>
<a
href=""
class="preview-link"
>
<h1>{{ article.title }}</h1>
<p>{{ article.description }}</p>
<span>Read more...</span>
</a>
</div>
</div>
<div class="col-md-3">
<div class="sidebar">
<p>Popular Tags</p>
<div class="tag-list">
<a
href=""
class="tag-pill tag-default"
>programming</a>
<a
href=""
class="tag-pill tag-default"
>javascript</a>
<a
href=""
class="tag-pill tag-default"
>emberjs</a>
<a
href=""
class="tag-pill tag-default"
>angularjs</a>
<a
href=""
class="tag-pill tag-default"
>react</a>
<a
href=""
class="tag-pill tag-default"
>mean</a>
<a
href=""
class="tag-pill tag-default"
>node</a>
<a
href=""
class="tag-pill tag-default"
>rails</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { useArticles } from '../services/article/getArticle'
import { defineComponent, onMounted } from 'vue'
export default defineComponent({
name: 'Home',
setup() {
const { page, articlesCount, articles } = useArticles()
return {
articles,
articlesCount,
}
},
})
</script>

0
src/pages/articles.ts Normal file
View File

14
src/routes.ts Normal file
View File

@ -0,0 +1,14 @@
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from './pages/Home.vue'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/my-feeds', component: Home },
{ path: '/tag/:tag', component: Home },
],
})
export default router

View File

@ -0,0 +1,36 @@
import { ref, watchEffect } from 'vue'
import { limit, request } from '../index'
export async function getArticle(slug: string) {
return request.get<ArticleResponse>(`/articles/${slug}`).then(res => res.article)
}
export async function getArticles(page = 1) {
const params = { limit, offset: (page - 1) * limit }
return request.get<ArticlesResponse>('/articles', { params })
}
export function useArticles() {
const articles = ref<Article[]>([])
const articlesCount = ref(0)
const page = ref(1)
async function fetchArticles() {
articles.value = []
articlesCount.value = 0
const response = await getArticles(page.value)
articles.value = response.articles
articlesCount.value = response.articlesCount
}
watchEffect(() => {
fetchArticles()
})
return {
articles,
articlesCount,
page
}
}

View File

@ -0,0 +1,18 @@
import { request } from '../index'
interface PostArticleForm {
title: string;
description: string;
body: string;
tagList: string[];
}
export async function postArticle(form: PostArticleForm) {
return request.post<ArticleResponse>('/articles', { article: form })
.then(res => res.article)
}
export async function putArticle(slug: string, form: PostArticleForm) {
return request.put<ArticleResponse>(`/articles/${slug}`, { article: form })
.then(res => res.article)
}

View File

@ -1,13 +1,12 @@
import FetchRequest from './utils/request'
import parseStorageGet from './utils/parse-storage-get'
import FetchRequest from '../utils/request'
import parseStorageGet from '../utils/parse-storage-get'
export const limit = 10
export const request = new FetchRequest({
prefix: `${process.env.API_HOST}/api`,
prefix: `${import.meta.env.VITE_API_HOST}/api`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Token ${parseStorageGet('user')?.token}`,
},
})
@ -32,31 +31,9 @@ export async function getAllTags() {
return request.get<TagsResponse>('/tags').then(res => res.tags)
}
interface PostArticleForm {
title: string;
description: string;
body: string;
tagList: string[];
}
export async function postArticle(form: PostArticleForm) {
return request.post<ArticleResponse>('/articles', { article: form })
.then(res => res.article)
}
export async function getArticle(slug: string) {
return request.get<ArticleResponse>(`/articles/${slug}`).then(res => res.article)
}
export async function putArticle(slug: string, form: PostArticleForm) {
return request.put<ArticleResponse>(`/articles/${slug}`, { article: form })
.then(res => res.article)
}
export async function getArticles(page = 1) {
const params = { limit, offset: (page - 1) * limit }
return request.get<ArticlesResponse>('/articles', { params })
}
export async function getFeeds(page = 1) {
const params = { limit, offset: (page - 1) * limit }

11
src/shimes-vue.d.ts vendored
View File

@ -1,5 +1,12 @@
declare module '*.vue' {
import Vue from 'vue'
import { defineComponent } from 'vue'
const Component: ReturnType<typeof defineComponent>
export default Vue
export default Component
}
interface ImportMeta {
env: {
VITE_API_HOST: string
}
}

View File

@ -1,3 +1,5 @@
import parseStorageGet from './parse-storage-get'
interface FetchRequestOptions {
prefix: string;
headers: Record<string, any>;
@ -48,6 +50,10 @@ export default class FetchRequest {
}
get<T = any>(url: string, options: Partial<FetchRequestOptions> = {}): Promise<T> {
options.headers = options.headers ?? {}
const token = parseStorageGet('user')?.token
if (token) options.headers['Authorization'] = `Token ${token}`
const finalUrl = this.generateFinalUrl(url, options)
return fetch(finalUrl, {
method: 'GET',
@ -57,6 +63,10 @@ export default class FetchRequest {
}
post<T = any>(url: string, data: Record<string, any> = {}, options: Partial<FetchRequestOptions> = {}): Promise<T> {
options.headers = options.headers ?? {}
const token = parseStorageGet('user')?.token
if (token) options.headers['Authorization'] = `Token ${token}`
const finalUrl = this.generateFinalUrl(url, options)
return fetch(finalUrl, {
@ -68,6 +78,10 @@ export default class FetchRequest {
}
delete<T = any>(url: string, options: Partial<FetchRequestOptions> = {}): Promise<T> {
options.headers = options.headers ?? {}
const token = parseStorageGet('user')?.token
if (token) options.headers['Authorization'] = `Token ${token}`
const finalUrl = this.generateFinalUrl(url, options)
return fetch(finalUrl, {
@ -78,6 +92,10 @@ export default class FetchRequest {
}
put<T = any>(url: string, data: Record<string, any> = {}, options: Partial<FetchRequestOptions> = {}): Promise<T> {
options.headers = options.headers ?? {}
const token = parseStorageGet('user')?.token
if (token) options.headers['Authorization'] = `Token ${token}`
const finalUrl = this.generateFinalUrl(url, options)
return fetch(finalUrl, {
@ -89,6 +107,10 @@ export default class FetchRequest {
}
patch<T = any>(url: string, data: Record<string, any> = {}, options: Partial<FetchRequestOptions> = {}): Promise<T> {
options.headers = options.headers ?? {}
const token = parseStorageGet('user')?.token
if (token) options.headers['Authorization'] = `Token ${token}`
const finalUrl = this.generateFinalUrl(url, options)
return fetch(finalUrl, {

View File

@ -2,8 +2,8 @@
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"target": "es5",
"module": "ESNext",
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
@ -17,13 +17,13 @@
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
"noEmit": true, /* Do not emit outputs. */
"noEmit": true,
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
"isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
"isolatedModules": true,
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"strict": true,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
@ -39,14 +39,12 @@
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
@ -61,8 +59,10 @@
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
"include": [
"src"
]
}