Nuxt — blog project(static)

Tinghuan Wang
summer's code life
Published in
5 min readJun 15, 2020

因為學習了基礎的Nuxt 語法Pages/Routing/Views,現在要來用這幾個特性建立blog(static)。程式碼位置

create nuxt 專案

$ npx create-nuxt-app <my-project>

建立pages(routers)

建立admin、posts、about這些path,也就是說建立這些folder,admin 用來登入和登出,posts 用來發表文章,about 關於的網頁。

about > index.vue

scoped 代表的是這個style 只適用這個component。

posts > _id > index.vue

接著在網址輸入http://localhost:3000/posts/1 就可以看到以下畫面

載入共用的css

我們使用google font 來當公版css,https://fonts.google.com/。選擇一個font,在html 中使用以下的語法就可以使用此style。

<link href="https://fonts.googleapis.com/css2?family=Balsamiq+Sans:wght@700&display=swap" rel="stylesheet">

可是我們並沒有.html 檔案,所以這時候就要使用package-lock.json 設定,修改head > link 設定

link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Balsamiq+Sans:wght@700&display=swap' }
]

這樣每一個頁面都有這個css 設定。

接著在修改layouts > default.vue ,style 改成以下內容

html{
font-family: 'Balsamiq Sans', sans-serif;
}
body {
margin:0
}

可以看到網頁的font 已經改變了

Use nuxt-link

現在修改pages > index.vue 檔案內容,這邊使用nuxt-link,這樣這個連結就是spa。

Use Component > Posts

剛剛index.vue 內容有重複的程式 > article 的部分。現在我們將article內容變成Component。

先移除Component底下的Logo.vue檔案,因為我們不需要,並且建立一個Posts 資料夾,Posts 資料夾底下建立一個PostPreview.vue 檔案。把剛剛index.vue 裡面 nuxt-link tag 和相對應的style移到PostPreview.vue。

使用props來取得來自index.vue傳遞的參數,這是vue 的特性。
name 是debug的時候比較容易。

再將index.vue 引用 PostPreview.vue Component。

@/ 的意思為指到root folder,也可以使用~/,此語法是告訴webpack 指向root。

使用PostPreview 要給定四個值,id、title、previewText、thumbnail。

Use assets

新增一個背景圖,圖片放到assets > images (images 可以自行定義名稱),裡面放一張圖片

pages > index.vue > .intro 加上css background-image: url(‘~assets/images/original.jpg’)

Use Component > Header

components 新增Navigation資料夾,裡面放三個component vue 檔案,檔案下載位置。因為想要每個頁面都載入Header component,因此我們將component放在layouts > default.vue 檔案。

TheHeader 有監聽sidenavToggle 事件,因此我們在layouts > default.vue 使用TheHeader component 加上@sidenavToggle=”displaySidenav = !displaySidenav”

Nuxt router linkActiveClass

  • Type: String
  • Default: 'nuxt-link-active'

Globally configure <nuxt-link> default active class.

Example (nuxt.config.js):

export default {
router: {
linkActiveClass: 'active-link'
}
}

This option is given directly to the vue-router linkactiveclass.

--

--