nuxt 정리

해피데빙·2022년 11월 23일
0

nuxt

  • context and helpers
    : context의 역할
  • directory structure
    : views
    : app.html
    - nuxt는 페이지 기반으로 작동
    - 웹 서비스의 구성상 페이지가 개별적으로 구성된다면 서비스 개발 시 많은 시간 소요
    - 공동 요소에 대한 로딩이 없으면 페이지 렌더링에도 많은 시간 소요
    그러므로 프로젝트 구조에 대한 효율성을 위해 Nuxt.js의 views/
    : error.html
    : pages
    : components
    : assets
    : static
    : layout
    ex. header, footer처럼 공통으로 들어가는 요소를 매번 렌더링하지 않을 수 있도록 한번에 담아 제공
    레이아웃을 포함하는 문서를 만들기 위해 html file에 대한 기본 양식 만들 수 있다 : document
    : default.vue
    : custom.vue
    : error.vue
    : nuxt.config.js
    : package.json
  • life cycle
  • routers/루트/_slug

정보 한페이지 설명
대학백과 예시

Views


document : app.html 파일 생성해서 커스터마이징
프로젝트 최상위
app.html : 도큐먼트 커스터마이징

html head : headers, html attrs를 갱신하기 위해 vue-meta사용
nuxt에서는 vue-meta를 아래 옵션으로 구성

{
  keyName: 'head', 
  // the component option name that vue-meta looks for meta info on.
  attribute: 'data-n-head', 
  // the attribute name vue-meta adds to the tags it observes
  ssrAttribute: 'data-n-head-ssr', 
  // the attribute name that lets vue-meta know that meta info has already been server-rendered
  tagIDKeyName: 'hid' 
  // the property name that vue-meta uses to determine whether to overwrite or append a tag
}

layout/default.vue : template 안에 nuxt 사용. nuxt 태그에 다른 page component들이 나온다. 해당 레이아웃은 서비스의 모든 페이지에 노출이 된다
ex. 대학백과 : include: [] 페이지 캡쳐

layout/error.vue : Nuxt 컴포넌트를 포함하지 않는다.

Context

  • 현재 요청에 대한 정보를 가지고 있음 ex. Vuex store에 바로 접근 가능
    : It provides a store object which can be treated as this.$store in Vue components.

  • ssr에서는 req, res 객체로 접근 가능, rotue, params, query, 환경변수, context.app.모듈로 접근 가능 ex. context.app.$http
    구조분해로 사용


asyncData, plugins, middleware, nuxtServerInit 과 같은 nuxt 함수에서 사용 가능

helper
#1.nuxtthis.nuxt this.nuxt로 접근 가능
기능
1. 인터넷 연결이 되어 있는지 없는지
: isOffline, isOnline

  1. 모든 컴포넌트에서 루트 인스턴스에 접근 가능
    you can also access the nuxthelperthroughwindow.nuxt helper through window.nuxt which can be used as an escape hatch to gain access to module methods like $axios from outside your Vue components. This should be used wisely and only as last resort.

  2. 현재 페이지 refresh하되 전체 reload를 하지 않고 싶을 때 사용
    : data만 새롭게 받아오고 싶을 때
    : this.$nuxt.refresh()를 통해 asyncData에서 갱신하고 있는 데이터 받아온다

#2. process
global process 객체에 client, server, static 세가지 불리언 값을 넣어준다
process.client / process.server / process.static을 통해 ssr인지 csr인지 확인 가능. static site generation도 확인 가능

어디서든 사용 가능, asyncData에서 많이 사용

<script>
	export default { 
    	asyncData(){ 
        	return { renderedOn : process.client ? 'client' : 'server'}
        }
    }
</script>

In the example, renderedOn will evaluate to 'server' when using server-side rendering and a user accesses the page directly.

When the user would navigate to the page from another part of the application, e.g. by click on a <NuxtLink>, it will evaluate to client.

Server side rendering

the ability of an application to contribute by displaying the web-page on the server instead of rendering it in the browser.

Server-side sends a fully rendered page to the client; the client's JavaScript bundle takes over which then allows the Vue.js app to hydrate.

node.js server가 필요하다
serverMiddleware를 통해 server를 확장시키고 middleware로 route를 컨트롤 가능

???

ssr를 사용하면 req, res에 접근 가능 / window, document에 접근 불가능 (브라우저니까). 대신 beforeMount, mounted 후크 통해 접근 가능

beforeMount(){ 
	window.alert('hello')
}
mounted(){ 
	window.alert('hello')
}

ssr하는 방법
1. 브라우저 -> 서버 : nuxt가 html 생성해서 브라우저에게 전송.
2. 서버 -> 브라우저 : 서버에서 생성된 html + vue.js hydration(페이지를 reactive, interactive하게 만들어준다)

cf. client hydration (https://vuejs.org/guide/scaling-up/ssr.html)
서버에서 보내주는 html은 아직 브라우저에서 vue를 이용하고 있지 않기 때문에 static하다
그러므로 interactive하게 만들어줄려면 hydration을 해줘야 한다

서버에서 실행된 것과 같은 Vue 애플리케이션을 만들어서 각 컴포넌트들을 DOM 노드에 연결하고
이벤트 리스너들을 추가한다

이렇게 hydration mode를 쓸거면 createApp이 아니라 createSSRApp() 사용

// this runs in the browser.
import { createSSRApp } from 'vue'

const app = createSSRApp({
  // ...same app as on server
})

// mounting an SSR app on the client assumes
// the HTML was pre-rendered and will perform
// hydration instead of mounting new DOM nodes.
app.mount('#app')

Notice how we need to reuse the same app implementation as on the server. This is where we need to start thinking about code structure in an SSR app - how do we share the same application code between the server and the client?

Here we will demonstrate the most bare-bones setup. First, let's split the app creation logic into a dedicated file, app.js

  1. 브라우저 -> 브라우저 :
    nuxtLink는 브라우저를 refresh하지 않는 이상 서버까지 올 필요 없이 바로 브라우저 안에서만 왔다갔다 할 수 있게 한다

SSR ㅜ

  • csr : produce and manipulate DOM in the browser as output
  • ssr :
    1) render the same components into HTML strings on the server
    2) send them directly to the browser
    3) hydrate the static markup into a fully interactive app on the client

장점
1. 빠르게 내용을 보여준다 (time-to-content): 아주 빠르게 화면에 나와야 할 때 사용한다
2. 전체 같은
3. SEO

단점
1. 서버 부담
2. build setup and deployment requirements
3. deve

SSG (= pre-rendering)

  • 빠른 웹사이트를 만들 때 쓰는 또 다른 방법

  • 페이지를 server-render하기 위해 필요한 데이터가 모든 사용자에게 같으면 요청마다 새롭게 렌더링할 필요 없이 빌드 때 렌더링하고 사용하면 좋다

  • static html 파일로 만들어서 제공된다

  • ssr과 같은 성격

  • great time-to-content performance

  • cheaper and easier to deploy than ssr apps : output이 static html & assets이니까

  • can only be applied to pags consuming static data (q

profile
노션 : https://garrulous-gander-3f2.notion.site/c488d337791c4c4cb6d93cb9fcc26f17

0개의 댓글