Skip to content

Commit

Permalink
refactor: 组合式api还挺好用的
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Oct 26, 2023
1 parent 63aebfb commit b6727c7
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 175 deletions.
32 changes: 30 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/home/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// <reference types="vite/client" />

import {StateTree} from 'pinia'
import {PageContext} from 'vike/types'
import {RouteLocationNormalizedLoaded} from 'vue-router'
import {Store} from 'vuex'
Expand All @@ -24,6 +25,7 @@ declare module 'vue' {
declare global {
interface Window {
__INITIAL_STATE__: object
__pinia: Record<string, StateTree>
}
}

Expand Down
3 changes: 2 additions & 1 deletion packages/home/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
},
"dependencies": {
"@element-plus/icons-vue": "^2.1.0",
"@nuxt/devalue": "^2.0.2",
"@sindresorhus/is": "^6.0.1",
"@vue/server-renderer": "^3.2.45",
"@vue/shared": "^3.3.4",
"animate.css": "^3.7.2",
"core-js": "^3.8.3",
"devalue": "^4.3.2",
"element-plus": "^2.4.1",
"font-awesome": "^4.7.0",
"http-errors": "^2.0.0",
Expand All @@ -36,6 +36,7 @@
"mavon-editor": "^3.0.0-beta",
"pinia": "^2.1.7",
"prismjs": "^1.29.0",
"type-fest": "^4.6.0",
"vue": "^3.2.45",
"vue-fetch": "^3.0.0-2",
"vue-router": "^4.2.5",
Expand Down
5 changes: 4 additions & 1 deletion packages/home/src/_default.page.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import {createHome} from './entries'
import './utils/prism.ts'

export async function render(pageContext: PageContext): Promise<void> {
const {app, router, store} = createHome()
const {app, router, store, pinia} = createHome()
if (window.__pinia) {
pinia.state.value = window.__pinia
}
app.config.globalProperties.$pageContext = pageContext
if (window.__INITIAL_STATE__) {
// We initialize the store state with the data injected from the server
Expand Down
9 changes: 5 additions & 4 deletions packages/home/src/_default.page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
'use strict'
import {renderToString} from '@vue/server-renderer'
import * as devalue from 'devalue'
import devalue from '@nuxt/devalue'
import * as HttpErrors from 'http-errors'
import {dangerouslySkipEscape, escapeInject} from 'vike/server'
import {PageContext} from 'vike/types'
Expand Down Expand Up @@ -39,12 +39,12 @@ export async function render(pageContext: PageContext) {
throw new HttpErrors.NotFound('no such route')
}
const rootState = useRootStore(pinia)
rootState.setOrigin(pageContext.origin)
rootState.setReferer(pageContext.referer)
await Promise.all(
matchedComponents.map(async (component) => {
if (!component) return null
if ('asyncData' in component && component.asyncData) {
rootState.setOrigin(pageContext.origin)
rootState.setReferer(pageContext.referer)
return component.asyncData({
store,
route: router.currentRoute.value,
Expand Down Expand Up @@ -73,7 +73,8 @@ export async function render(pageContext: PageContext) {
<meta name="description" content="${desc}" />
<title>${title}</title>
<script>
window.__INITIAL_STATE__ = ${dangerouslySkipEscape(devalue.uneval(pageContext.state))}
window.__INITIAL_STATE__ = ${devalue(pageContext.state)}
window.__pinia = ${devalue(pinia.state.value)}
</script>
</head>
<body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
</h2>
<div class="freyja-article-list">
<article
v-for="article in articles"
v-for="article in homeStore.articles"
:key="article._id"
>
<h3 class="freyja-article-title">
Expand Down Expand Up @@ -60,84 +60,71 @@
</div>
</div>
</template>
<script lang="ts">
<script lang="ts" setup>
import {ElButton} from 'element-plus'
import {defineComponent} from 'vue'
import lozad from 'lozad'
import prismjs from 'prismjs'
import {computed, onMounted, onUpdated} from 'vue'
import {useRoute} from 'vue-router'
import {useHomeStore} from '../../store/home.ts'
const route = useRoute()
const homeStore = useHomeStore()
export default defineComponent({
name: 'HomeHome',
components: {
ElButton,
},
asyncData({store, route}) {
switch (route.name) {
case 'home':
return store.dispatch('home/getArticles', {page: route.query.page || 1})
case 'category':
return store.dispatch('home/getArticles', {
page: route.query.page || 1,
category: route.params.category,
})
case 'tag':
return store.dispatch('home/getArticles', {
page: route.query.page || 1,
tag: route.params.tag,
})
case 'search':
return store.dispatch('home/search', {
keyword: route.query.keyword,
page: route.query.page || 1,
})
default:
}
},
data() {
const result = {
articles: this.$store.state.home.articles,
page: Number(this.$route.query.page) || 1,
tag: this.$route.params.tag,
category: this.$route.params.category,
keyword: this.$route.params.keyword,
}
if (this.$route.name === 'search' && this.$route.query.keyword) {
result.keyword = this.$route.query.keyword.toString()
}
return result
},
computed: {
canGoBackward() {
return this.page > 1
},
canGoForward() {
return this.$store.getters['home/articleCount'] === 20
},
},
mounted() {
this.highlight()
import('lozad').then((lozad) => {
const observer = lozad.default()
observer.observe()
const page = typeof route.query.page === 'string' ? parseInt(route.query.page, 10) : 1
const tag = route.params.tag as string | undefined
const category = route.params.category as string | undefined
const keyword = route.params.keyword as string | undefined
switch (route.name) {
case 'home':
await homeStore.getArticles({page})
break
case 'category':
await homeStore.getArticles({
page,
category,
})
},
async updated() {
await this.highlight()
const lozad = await import('lozad')
lozad.default().observe()
},
methods: {
async highlight() {
const prismjs = await import('prismjs')
prismjs.highlightAll()
},
formatDate(date: Date | string): string {
if (typeof date === 'string') {
date = new Date(date)
}
return date.toLocaleString()
},
},
break
case 'tag':
await homeStore.getArticles({
page,
tag,
})
break
case 'search':
await homeStore.search({
keyword: keyword ?? '',
page,
})
break
default:
// no default
}
const canGoBackward = computed(() => page > 1)
const canGoForward = computed(() => homeStore.articles.length === 20)
onMounted(() => {
highlight()
const observer = lozad()
observer.observe()
})
onUpdated(() => {
highlight()
})
function highlight(): void {
prismjs.highlightAll()
}
function formatDate(date: Date | string): string {
if (typeof date === 'string') {
date = new Date(date)
}
return date.toLocaleString()
}
</script>
<style lang="scss">
.freyja-article-pager-prev {
Expand Down
8 changes: 4 additions & 4 deletions packages/home/src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function createHomeRouter(): Router {
const routes: RouteRecordRaw[] = [
{
path: '/',
component: () => import('../pages/home/home.vue'),
component: () => import('../pages/home/HomeIndex.vue'),
name: 'home',
},
{
Expand All @@ -28,17 +28,17 @@ export function createHomeRouter(): Router {
},
{
path: '/tag/:tag',
component: () => import('../pages/home/home.vue'),
component: () => import('../pages/home/HomeIndex.vue'),
name: 'tag',
},
{
path: '/category/:category',
component: () => import('../pages/home/home.vue'),
component: () => import('../pages/home/HomeIndex.vue'),
name: 'category',
},
{
path: '/search',
component: () => import('../pages/home/home.vue'),
component: () => import('../pages/home/HomeIndex.vue'),
name: 'search',
},
]
Expand Down
Loading

0 comments on commit b6727c7

Please sign in to comment.