NuxtJS 치트 시트 1

22417 단어 vuenuxtjavascript
헤이 DEV.to 커뮤니티!

이전에 Vue 치트 시트라는 시리즈를 게시했으며 여기에서 사용할 수 있습니다.




저는 주로 NuxtJS 이라는 프레임워크에서 Vue를 사용합니다. NuxtJS는 Vue를 기반으로 구축된 멋진 프레임워크입니다. 여기 NuxtJS를 시작하는 치트 시트가 있습니다.

일부 코드는 NuxtJS의 공식 웹사이트에서 가져온 것입니다.

내용의 테이블



  • Installation
  • Manually
  • Predefined structure

  • NuxtJS commands

  • Routing
  • Dynamic routes

  • Layouts
  • Errors page
  • Navigation

  • Context
  • Redirecting
  • Showing error


  • $nuxt
  • isOffline
  • refresh


  • 설치

    NuxtJS has two modes to get started. You can either create your own app and install NuxtJS as a dependency or use its predefined structure.

    수동으로

    You can create a folder and start your project using the npm init command and install NuxtJS as a dependency:

    npm i --save nuxt
    

    And create a folder in your project root called pages and add a file called index.vue in it with the content below:

    <template>
        <div>
            <h1>Hello Nuxt!</h1>
        </div>
    </template>
    

    미리 정의된 구조

    If you want NuxtJS to provide you with a starting structure so you just start coding and having fun you can use the command below:

    npx create nuxt-app <your-app-name>
    

    npx is installed along with npm, so don't worry!

    Run the command above and answer some questions (they are easy don't worry, you will pass!)

    I prefer this method personally.

    NuxtJS 명령

    Here is a list of common commands used in your Terminal/CMD/PowerShell to do something with NuxtJS!

    Launch a dev server:

    nuxt
    

    Build your application for production:

    nuxt build
    

    Launch a production server:

    nuxt start
    

    Generate a static website, meaning that every route will be a static HTML file:

    nuxt generate
    

    라우팅

    If you have ever set up a Vue project, you should know how much it takes to set up a proper routing. In NuxtJS, every Vue file inside the pages folder is a route instantly!

    Having a structure as below:

    |----pages/
        |----extra/
            |----index.vue
            |----about.vue
        |----index.vue
    

    Will create a route available as below:

    http://example.org/ => index.vue
    http://example.org/extra => extra/index.vue
    http://example.org/extra/about => extra/about.vue
    

    동적 경로

    A dynamic route can be defined using an underscore character prefixed in a directory or file name.

    Having a structure as below:

    |----pages/
        |----user/
            |----_id.vue
    

    Gives you a dynamic route as http://example.com/user/:id which in it the :id can be anything. You can retrieve the value of this parameter in your component using the asyncData method:

    <template>
        <div>
            <h1>Your id is {{ id }}</h1>
        </div>
    </template>
    
    <script>
        export default {
            async asyncData(context) {
                return {
                    id: context.params.id
                }
            }
        }
    </script>
    

    You can use the destructuring syntax of JavaScript and make the code above even simpler:

    <template>
        <div>
            <h1>Your id is {{ id }}</h1>
        </div>
    </template>
    
    <script>
        export default {
            async asyncData({ params }) {
                return {
                    id: params.id
                }
            }
        }
    </script>
    

    It is also possible to have a directory as a dynamic parameter holder:

    |----pages
        |----_user/
            |----index.vue
            |----posts.vue
    

    This makes you enable to create dynamic routes such as http://example.com/:user/ and http://example.com/:user/posts which is awesome!

    레이아웃

    Layouts are the way you can define a template structure for your pages that is common between them. To add a layout just add it to your layouts directory. If you name it default.vue it will be used as default.

    Always add the <NuxtChild> component to your layout so the content of the page using the layout gets rendered there.

    Here is a simple layout:

    <template>
        <div>
            <nuxt-child />
        </div>
    </template>
    

    You can use your custom layouts like this:

    <script>
        export default {
            layout: 'your-layout-name'
        }
    </script>
    

    오류 페이지

    You can customize the errors page of your NuxtJS application. The errors page is surprisingly located at layouts/error.vue while you should treat it as a page and not a layout! Which means you shouldn't include the <NuxtChild> component in it!

    You can get the error code inside your errors page using the error prop:

    <template>
        <div>
            Error code: {{ error.statusCode }}
        </div>
    </template>
    
    <script>
        export default {
            props: ['error']
        }
    </script>
    

    항해

    Navigation in a NuxtJS app is super easy. There is a very handy component called <NuxtLink> which you use as below:

    <template>
        <div>
            <nuxt-link to="/about">About</nuxt-link>
        </div>
    </template>
    

    문맥

    The context is an everywhere-present object which holds really useful stuff and is like a saving angel! But to be more precise it is only available in asyncData , plugins , middleware and nuxtServerInit .

    The context object is defined as below:

    const {
        app,
        store,
        route,
        params,
        query,
        env,
        isDev,
        isHMR,
        redirect,
        error,
        $config
      } = context
    

    The context object has some properties only available in the server-side:

    const {
        req,
        res,
        beforeNuxtRender
      } = context
    

    And some only available in the client-side:

    const {
        from,
        nuxtState,
      } = context
    

    리디렉션 중

    Redirecting is one of the most common tasks done by the context object's redirect method:

    <script>
        export default {
            middleware({ redirect }) {
                if (!someAuthentication) {
                    redirect('/login')
                }
            }
        }
    </script>
    

    오류 표시

    If you ever caught and error and wouldn't know what to do with it, just let context.error show it! The error method of the context object lets you pass an error to it and it shows it in your errors page:

    <script>
        export default {
            middleware({ error }) {
                try {
                    something()
                } catch (err) {
                    error(err)
                }
            }
        }
    </script>
    

    $nuxt

    The $nuxt object is available in your components via this.$nuxt and is available globally via window.$nuxt in case you wanted to use it outside of your components (which is discouraged and used as a last resort).

    isOffline

    There is a property called isOffline inside the $nuxt object which holds a boolean indicating the internet connection of the user. You can use it to show a disconnection message to user:

    <template>
        <div>
            <div v-if="$nuxt.isOffline">You are offline!</div>
        </div>
    </template>
    

    Oh! And there is one called isOnline which acts the opposite!

    새로 고치다

    In case you want to refresh the page's data (provided by asyncData and fetch ) you can simply use the refresh method of the $nuxt object and not hit the refresh button that hard!

    <template>
        <div>
            <button @click="refreshThePage">Refresh</button>
        </div>
    </template>
    
    <script>
        export default {
            methods: {
                refreshThePage() {
                    this.$nuxt.refresh()
                }
            }
        }
    </script>
    

    This will save you some traffic as well if you are using a server-side rendered NuxtJS application since this refresh won't hit the server again for rendering the page opposite of hard-refreshing the page.


    I hope you enjoyed this cheat sheet! More is coming.

    Check out my free Node.js Essentials E-book here:


    좋은 웹페이지 즐겨찾기