https://nuxtjs.org/docs/concepts/server-side-rendering#window-or-document-undefined

 

Server Side Rendering

Server-side rendering (SSR), is the ability of an application to contribute by displaying the web-page on the server instead of rendering it in the browser.

nuxtjs.org

 

Nuxt.js에서 window 객체를 사용을 하려면 문제가 생긴다. 

 

window is undefined

window is undefined

 

 

원인의 오류는 Nuxt.js는 SSR (Server Side Rendering)이기 때문이다. 

 

처음에 nuxt를 실행하면 각종 설정과 lifecycle을 실행하게 되는데 이때, Server Side에는 window 객체가 없으므로 문제가 생기는 것이다. 

 

이런 오류를 종종 본다. html에서는 <client-only>를 통해 해결할 수 있다. 

 

데이터에서는 process.client 를 사용할 수 있다. client side rendering일 때, 실행시키라는 의미이다. 

 

 

'Front-End > Vue & Nuxt' 카테고리의 다른 글

Nuxt.js Quill Editor  (0) 2022.03.04
Nuxt.js Auth (Naver)  (0) 2022.03.01
Nuxt.js Lottie 사용하기  (0) 2022.02.27
Eslint Babel정리  (0) 2022.02.27
Nuxt.js Buefy Pagination  (0) 2022.02.26

Quill Editor 공식 사이트

https://quilljs.com/

 

Quill - Your powerful rich text editor

Sailec Light Sofia Pro Slabo 27px Roboto Slab Inconsolata Ubuntu Mono Quill Rich Text Editor Quill is a free, open source WYSIWYG editor built for the modern web. With its modular architecture and expressive API, it is completely customizable to fit any ne

quilljs.com

 

 

Vue-Quill-Editor

 

Vue 

https://github.com/surmon-china/vue-quill-editor

 

Nuxt 

https://github.com/surmon-china/surmon-china.github.io/tree/source/projects/vue-quill-editor/nuxt

 

 

적용 가이드 (중국어 주의)

https://hamsterism.com/articles/how-to-use-vue-quill-editor-in-nuxt/

 

 

1. 필요 모듈 설치

 

npm install vue-quill-editor --save 
# 또는 
yarn add vue-quill-editor

# 추가
npm i vue-debounce
yarn add vue-debounce

 

 

2. Plugin file 생성

 

plugins/vue-quill-editor.js

import Vue from 'vue'
import VueQuillEditor from 'vue-quill-editor'

Vue.use(VueQuillEditor)

 

 

3. Nuxt.config 정의

 

nuxt.config.js

  css: [
    'quill/dist/quill.snow.css',
    'quill/dist/quill.bubble.css',
  ],
  
  plugins: [{ src: '~plugins/vue-quill-editor.js', ssr: false }],

 

 

4. Quill.vue 생성

 

<template>
  <section>
    <client-only>
      <quill-editor
        ref="editor"
        v-model.lazy="editedContent"
        :options="editorOption"
        class="editor--border relative"
        @change="debounceTextChange"
      />
    </client-only>
  </section>
</template>

<script>
import { debounce } from 'vue-debounce'
export default {
name: "QuillEditor",
  props: {
    content: {
      type: String,
      default: () => '',
    },
  },
  data() {
    return {
      editedContent: this.content,
      editorOption: {
          theme: 'snow',
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block']
            ]
          }
      }

	// custom
      editorOption: {
        theme: 'bubble',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike', 'code'],
              ['blockquote', 'code-block'],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ script: 'sub' }, { script: 'super' }],
              [{ indent: '-1' }, { indent: '+1' }],
              [{ size: ['small', false, 'large', 'huge'] }],
              [{ color: [] }, { background: [] }],
              [{ align: [] }],
              ['clean'],
              ['link', 'image', 'video'],
            ],
            handlers: {
              image: this.uploadImage,
            },
          },
        },
      },
    }
  },
  methods: {
    debounceTextChange: debounce(function () {
      // don't use arrow function
      this.$emit('text-change', this.editedContent)
    }, 3000),
  },
}
</script>

https://github.com/dhershman1/vue-debounce#readme

https://pks2974.medium.com/throttle-%EC%99%80-debounce-%EA%B0%9C%EB%85%90-%EC%A0%95%EB%A6%AC%ED%95%98%EA%B8%B0-2335a9c426ff

 

Throttle 와 Debounce 는 자주 사용 되는 이벤트나 함수 들의 실행되는 빈도를 줄여서, 성능 상의 유리함을 가져오기 위한 개념이다.

 

 

'Front-End > Vue & Nuxt' 카테고리의 다른 글

Nuxt.js window or document undefined  (0) 2022.03.05
Nuxt.js Auth (Naver)  (0) 2022.03.01
Nuxt.js Lottie 사용하기  (0) 2022.02.27
Eslint Babel정리  (0) 2022.02.27
Nuxt.js Buefy Pagination  (0) 2022.02.26

https://auth.nuxtjs.org/schemes/oauth2

 

Introduction

Zero-boilerplate authentication support for Nuxt.js!

auth.nuxtjs.org

https://vicapor.tistory.com/80

 

nuxt.config.js

      naver: {
        scheme: 'oauth2',
        clientId: process.env.NAVER_CLIENT_ID,
        codeChallengeMethod: '',
        responseType: 'code',
        // grantType: 'authorization_code',
        endpoints: {
          authorization: 'https://nid.naver.com/oauth2.0/authorize',
          token: `${baseURL}/social-login/naver/`,
          userInfo: `${baseURL}/user/`,
        },
        token: {
          property: 'access_token',
          type: 'Bearer',
          maxAge: 18000
        },
      },

 

this.$auth.loginWith("naver");

 

 

https://auth.nuxtjs.org/api/auth

 

Introduction

Zero-boilerplate authentication support for Nuxt.js!

auth.nuxtjs.org

 

'Front-End > Vue & Nuxt' 카테고리의 다른 글

Nuxt.js window or document undefined  (0) 2022.03.05
Nuxt.js Quill Editor  (0) 2022.03.04
Nuxt.js Lottie 사용하기  (0) 2022.02.27
Eslint Babel정리  (0) 2022.02.27
Nuxt.js Buefy Pagination  (0) 2022.02.26

https://medium.com/@fonto.design/using-lottie-in-nuxt-js-554949d19063

 

Using Lottie in Nuxt.js

There is no Lottie plugin for Nuxt, but you can install “vue-lottie” instead. I am writing this article because I cannot find a proper doc…

medium.com

https://github.com/chenqingspring/vue-lottie

 

GitHub - chenqingspring/vue-lottie: Render After Effects animations on Vue based on Bodymovin

Render After Effects animations on Vue based on Bodymovin - GitHub - chenqingspring/vue-lottie: Render After Effects animations on Vue based on Bodymovin

github.com

 

vue-lottie 설치

 

 

npm install --save vue-lottie

or

yarn add vue-lottie

 

 

적용

 

<template>
    <!-- width and height are optional -->
    <lottie :width="1024" :height="1024" :options="lottieOptions" v-on:animCreated="handleAnimation" />
</template>


import lottie from 'vue-lottie/src/lottie.vue'
import * as animationData from "~/assets/animation.json";
export default {
  components: {
    lottie
  },
  data() {
    return {
      anim: null, // for saving the reference to the animation
      lottieOptions: { animationData: animationData.default }
    };
  },
  methods: {
    handleAnimation: function (anim) {
      this.anim = anim;
    }
  }
}

 

 

기본 사용법 + 옵션설정

 

<template>
    <div id="app">
        <lottie :options="defaultOptions" :height="400" :width="400" v-on:animCreated="handleAnimation"/>
        <div>
            <p>Speed: x{{animationSpeed}}</p>
            <input type="range" value="1" min="0" max="3" step="0.5"
                   v-on:change="onSpeedChange" v-model="animationSpeed">
        </div>
        <button v-on:click="stop">stop</button>
        <button v-on:click="pause">pause</button>
        <button v-on:click="play">play</button>
    </div>
</template>

<script>
  import Lottie from './lottie.vue';
  import * as animationData from './assets/pinjump.json';

  export default {
    name: 'app',
    components: {
      'lottie': Lottie
    },
    data() {
      return {
        defaultOptions: {animationData: animationData},
        animationSpeed: 1
      }
    },
    methods: {
      handleAnimation: function (anim) {
        this.anim = anim;
      },

      stop: function () {
        this.anim.stop();
      },

      play: function () {
        this.anim.play();
      },

      pause: function () {
        this.anim.pause();
      },

      onSpeedChange: function () {
        this.anim.setSpeed(this.animationSpeed);
      }
    }
  }
</script>

 

 

추가) Component화

 

사용법대로 사용해도 작동은 하나 불편한 점이 있다. lottie를 다양한 페이지에서 사용하고 싶을 때에 직접 lottie파일을 import해야한다는 점이다. 그래서 Nuxt에서 사용할 컴포넌트로 바꿔보았다.

 

Lottie.vue

<template>
  <div>
    <lottie
      :options="defaultOptions"
      :height="400"
      :width="400"
      @animCreated="handleAnimation"
    />
  </div>
</template>

<script>
import lottie from 'vue-lottie/src/lottie.vue';

export default {
  name: 'LottieComponent',
  components: {
    lottie
  },
  props: {
    animationData: {
      type: String,
      required: true,
    }
  },
  data() {
    return {
      defaultOptions: { animationData: null },
      animationSpeed: 1,
    }
  },
  created() {
    this.defaultOptions.animationData = require("~/assets/lottie/test-lottie.json");
  },

  methods: {
    handleAnimation (anim) {
      this.anim = anim;
    },

    stop() {
      this.anim.stop()
    },

    play() {
      this.anim.play()
    },

    pause() {
      this.anim.pause()
    },

    onSpeedChange() {
      this.anim.setSpeed(this.animationSpeed)
    },
  },
}
</script>

 

이제 모든 페이지에서 다음과 같이 사용할 수 있다.

<Lottie animation-data="~/assets/lottie/test-lotte.json" />

 

'Front-End > Vue & Nuxt' 카테고리의 다른 글

Nuxt.js Quill Editor  (0) 2022.03.04
Nuxt.js Auth (Naver)  (0) 2022.03.01
Eslint Babel정리  (0) 2022.02.27
Nuxt.js Buefy Pagination  (0) 2022.02.26
Nuxt.js 유용한 모듈 정리  (0) 2022.02.26

https://eslint.org/

외부 모듈

 

globals

 

nuxt.config.js에서 전역으로 script를 선언하고 페이지나 컴포넌트에서 사용하려고 하면 no-def 오류가 발생한다. 

이럴경우 eslint의 설정을 바꿔주는 것으로 해결 할 수 있다.

 

.eslintrc.js

  ...
  "globals": {
    'daum': true
  }

 

또한 외부 모듈파일인 js 파일도 eslint를 적용시키는데 .eslintignore 파일을 통해 무시할 수 있다.

 

.eslintignore

static/vendor/brython/brython-runner.bundle.js

 

console.log

https://eslint.org/docs/rules/no-console

 

eslint에서 console.log를 사용하면 경고를 표시한다.

{
    "rules": {
        "no-console": "off",
        "no-restricted-syntax": [
            "error",
            {
                "selector": "CallExpression[callee.object.name='console'][callee.property.name!=/^(log|warn|error|info|trace)$/]",
                "message": "Unexpected property on console object was called"
            }
        ]
    }
}

을 통해 console.log에 대한 경고 표시를 종료할 수 있다.

'Front-End > Vue & Nuxt' 카테고리의 다른 글

Nuxt.js Auth (Naver)  (0) 2022.03.01
Nuxt.js Lottie 사용하기  (0) 2022.02.27
Nuxt.js Buefy Pagination  (0) 2022.02.26
Nuxt.js 유용한 모듈 정리  (0) 2022.02.26
Nuxt.js SCSS 사용  (0) 2022.02.26

Buefy의 Pagination을 이용해서 Nuxt에서 pagination을 구현해보려고 한다.

 

<template>
    <section>
        <b-pagination
            :total="200" <!-- 전체 아이템 갯수 -->
            v-model="current"
            :per-page="10"> <!-- 페이지당 아이템 갯수 -->

            <template #default="props">
                <b-pagination-button
                    :page="props.page"
                    :id="`page${props.page.number}`"
                    tag="router-link"
                    :to="`/documentation/pagination#page${props.page.number}`"> <!-- hash를 사용한 url -->
                    {{ props.page.number }}
                </b-pagination-button>
            </template>


            <template #previous="props">
                <b-pagination-button
                    :page="props.page"
                    tag="router-link"
                    :to="`/documentation/pagination#page${props.page.number}`">
                    Previous
                </b-pagination-button>
            </template>

            <template #next="props">
                <b-pagination-button
                    :page="props.page"
                    tag="router-link"
                    :to="`/documentation/pagination#page${props.page.number}`">
                    Next
                </b-pagination-button>
            </template>

        </b-pagination>
    </section>
</template>

<script>
    export default {
        data() {
            return {
                current: 10,
            }
        },
        watch: {
            $route: {
                immediate: true,
                handler(newVal, oldVal) {
                    if (newVal.hash) {
                        this.current = parseInt(newVal.hash.replace(/#page/g, '')) // url에서 #page 를 ''로 바꾸고 남은 숫자 (페이지 숫자를 가져온다.)
                    }
                },
            },
        }
    }
</script>

참고)

 

Replace()에서 치환을 당담하는것은, 정규식의 g 부분이다. 해당위치에 오는 문자에 따라서

g : 문자열 내의 모든 패턴 체크

i : 대소문자를 구별하지 않음

m : 여러줄에 걸쳐서 체크

 

 

v-for="(item, idx) in posts.slice(sliceStart, sliceEnd)"

slice를 통해 데이터를 자른다음에 보여주면 된다. 페이지네이션이 되면 hash값으로 숫자를 얻을 수 있기 때문에 이를 계산하는 함수로 데이터를 처리해주면 된다. 

 

ex) 만약에 페이지당 10개씩 데이터를 보여주게 된다면 sliceStart는 0이되고 sliceEnd는 10이 된다. 이후에 페이지 네이션이 될때마다 계산을 해주면 되는데 

 

sliceEnd = 페이지네이션 번호 * 페이지당 보여줄 데이터 수

sliceStart = sliceEnd - 페이지당 보여줄 데이터 수

 

이런 함수를 만들어서 계산하면 된다.

'Front-End > Vue & Nuxt' 카테고리의 다른 글

Nuxt.js Lottie 사용하기  (0) 2022.02.27
Eslint Babel정리  (0) 2022.02.27
Nuxt.js 유용한 모듈 정리  (0) 2022.02.26
Nuxt.js SCSS 사용  (0) 2022.02.26
Nuxt.js Transition  (0) 2022.02.26

+ Recent posts