반응형

NuxtJS 정적 사이트 배포하는 방법입니다.

:: Nuxt2 입니다.

:: Nuxt3 github pages 배포하기 바로가기

 

npm

$ npm install push-dir --save-dev

 

push-dir, github actions, Travis CI 등 방법은 여러가지 있습니다. ( 여기서는 push-dir을 사용했습니다. )

 

nuxt.config.js

export default {
  target: "static",
  router: {
    base: "/깃허브 레포지토리 이름/"
  },
}

 

github에서 Repository name에 적었던 이름입니다.

 

전제조건

  • github Repository
  • nuxt.config.js의 ssr값이 false

 

package.json

  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "deploy": "push-dir --dir=dist --branch=gh-pages --cleanup",
    "test": "jest"
  },

 

사실 deploy 한 줄 추가됐습니다.

 

배포파일 생성하기

$ npm run generate

 

저는 정적파일 배포를 하려고 했기 때문에 generate를 해주었습니다.

 

dist파일이 생성된 모습입니다.

 

github pages 브랜치에 업로드하기

$ npm run deploy

 

정상적으로 업로드가 완료되었다면 gh-pages 브랜치가 생성되고 내부에 dist 파일들이 업로드 되어있을 것입니다.

 

 

사이트 접속하기

https://shiro21.github.io/repository-name/

자신의 github.io에 repository-name을 붙여주면 배포한 사이트에 접속할 수 있습니다.

 

반응형

'VueJS > VueJS' 카테고리의 다른 글

[ Vue ] Vue3 defineEmits  (0) 2022.09.29
[ Vue ] Vue3 defineProps  (0) 2022.09.28
[ Vue ] Vue3 Vuex 상태 관리 패턴  (2) 2022.09.21
[ Vue ] Vue3 Global 변수  (1) 2022.09.21
[ Vue ] Vue3 scss 사용하기  (0) 2022.09.06
반응형

defineEmits

자식 컴포넌트에서 부모 컴포넌트로 데이터를 전달해 줄 때 사용하는 단방향 데이터 전달 방식입니다.

 

Child.vue ( MainHeader.vue )

// 검색 내용을 부모 컴포넌트에 전해주기 예

<script setup>
    import { onMounted, inject, ref, defineEmits } from '@vue/runtime-core'
    
    const emit = defineEmits(["create:input"]);
    
    const inputData = (e) => {
        emit('create:input', e.target.value)
    }
</script>

<template>
    <input type="text" @input="inputData($event)" placeholder="서치 바" />
</template>

 

Parent.vue

<script setup>
    import { ref } from 'vue'
    
    const text = ref('')
    const handleUpdate = (item) => {
        text.value = item
        console.log(text.value)
    }
</script>

<template>
    <MainHeader @create:input="handleUpdate" />
</template>

 

반응형

'VueJS > VueJS' 카테고리의 다른 글

[ Vue ] NuxtJS 정적 사이트 배포하기  (0) 2024.01.12
[ Vue ] Vue3 defineProps  (0) 2022.09.28
[ Vue ] Vue3 Vuex 상태 관리 패턴  (2) 2022.09.21
[ Vue ] Vue3 Global 변수  (1) 2022.09.21
[ Vue ] Vue3 scss 사용하기  (0) 2022.09.06
반응형

defineProps

부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달해 줄 때 사용하는 단방향 데이터 전달 방식입니다.

 

Parent.vue

<script setup>
    import ReadContents from '@/components/read/ReadContents.vue'
    const test = {
        id: 'hello',
        pass: 'world'
    }
</script>

<template>
    <ReadContents :test="test" />
</template>

 

Child.vue

<script setup>
    import { defineProps, onMounted, ref } from 'vue'
    
    const props = defineProps(['test'])
    console.log(props.test) // { id: "hello" pass: "world" }
    
</script>

 

반응형

'VueJS > VueJS' 카테고리의 다른 글

[ Vue ] NuxtJS 정적 사이트 배포하기  (0) 2024.01.12
[ Vue ] Vue3 defineEmits  (0) 2022.09.29
[ Vue ] Vue3 Vuex 상태 관리 패턴  (2) 2022.09.21
[ Vue ] Vue3 Global 변수  (1) 2022.09.21
[ Vue ] Vue3 scss 사용하기  (0) 2022.09.06
반응형

Vuex 개념

vuex는 뷰의 상태관리 라이브러리로 애플리케이션의 모든 컴포넌트에 저장소 역할을 하며, 의도적인 방법으로 상태를 변경 및 관리 할 수 있습니다. Vuex는 Flux의 아키텍처를 따라가고 있으며 React의 Redux와 비슷하다고 볼 수 있습니다.

 

규모가 작은 애플리케이션의 경우 Event Bus를 사용해도 무방하지만 규모가 커지면 관리가 어려워지므로 Vuex를 사용하는 것을 권장합니다.

 

 

 

Vuex 구조

Vuex는 state, mutations, action, getters의 4가지 형태로 관리가 되며, 이때 store패턴을 사용하고 통상 store라고 불립니다.

이 4가지는 서로간의 간접적인 영향이 있으며 단방향 데이터 흐름으로 볼 수 있습니다.

 

 

State

스테이트는 Vue 컴포넌트에서 data로 불 수 있습니다. 원본 소스의 역할을 하며, View와 직접적으로 연결되어 있는 Model이다. 이 스테이트는 직접적인 변경이 불가능하며, 뮤테이션을 통해 스테이트가 변경이 일어나면 반응적으로 View가 업데이트 됩니다.

 

 

Mutations

뮤테이션은 스테이트를 변경하는 방법이고 이벤트와 유사합니다. 뮤테이션은 함수로 구현되며 첫 번째 인자는 스테이트를 받을 수 있으며, 두 번째 인자는 payload를 받을 수 있습니다.

:: payload : 여러 필드를 포함할 수 있는 객체의 형태도 가능합니다. 뮤테이션은 일반적으로 직접 호출 할 수 없으며, commit을 통해서만 호출 할 수 있습니다.

 

store.commit('setData', payload)

 

 

Actions

액션은 뮤테이션과 비슷하지만 뮤테이션과 다르게 비동기 작업이 가능합니다. 또한 뮤테이션에 대한 commit이 가능하여 액션에서도 뮤테이션을 통해 스테이트를 변경할 수 있습니다. 액션에서는 첫 번째 인자를 context인자로 받을 수 있으며, 이 context에는 state, commit, dispatch, rootstate와 같은 속성들을 포함합니다. 두 번째 인자는 뮤테이션과 동일하게 payload로 받을 수 있습니다.

commit을 통해 뮤테이션을 호출했다면 액션은 dispatch를 통해서 호출합니다. context속성을 보면 dispatch가 있는 것으로 보아 액션에서는 서로 다른 액션을 호출할 수 있다는 것을 볼 수 있습니다.

 

store.dispatch('setData', payload)

 

 

Getters

게터는 쉽게 Vue 컴포넌트에서 computed로 볼 수 있습니다. 게터의 결과는 종속성에 따라 캐시되고 일부 종속성이 변경된 경우에만 다시 재계산됩니다. 즉, 특정 스테이트에 대해 어떤 연산을 하고 그 결과를 View에 바인딩할 수 있으며, 스테이트의 변경 여부에 따라 게터는 재계산 되고, View 역시 업데이트를 합니다. 이때 스테이트는 원본 데이터로서 변경이 일어나지 않습니다.

 

 

 

Vuex 설치하기

 

npm install

$ npm install vuex

 

반응형

'VueJS > VueJS' 카테고리의 다른 글

[ Vue ] Vue3 defineEmits  (0) 2022.09.29
[ Vue ] Vue3 defineProps  (0) 2022.09.28
[ Vue ] Vue3 Global 변수  (1) 2022.09.21
[ Vue ] Vue3 scss 사용하기  (0) 2022.09.06
[ Vue ] Vue3 vue-router  (0) 2022.09.06
반응형

1. app.config.globalProperties

 

main.js

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.config.globalProperties.$hello = "hello"

app.mount('#app')

 

app.vue

<script>
    import { defineComponent } from 'vue'
    
    export default defineComponent({
        mounted() {
            console.log(this.$hello) // hello
        }
    })
</script>

 

 

2. provide / inject

 

main.js

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.provide('$hello', 'hello')

app.mount('#app')

 

app.vue

<script setup>
    import { inject } from 'vue'
    
    console.log(inject('$hello')) // hello
</script>

 

반응형

'VueJS > VueJS' 카테고리의 다른 글

[ Vue ] Vue3 defineProps  (0) 2022.09.28
[ Vue ] Vue3 Vuex 상태 관리 패턴  (2) 2022.09.21
[ Vue ] Vue3 scss 사용하기  (0) 2022.09.06
[ Vue ] Vue3 vue-router  (0) 2022.09.06
[ Vue ] Vue3 Firebase firestore collection 전체 불러오기  (0) 2022.08.30
반응형

node-sass 바로가기

sass-loader 바로가기

 

npm install

$ npm install node-sass

$ npm install sass-loader

 

App.vue

<style scoped lang="scss">

</style>

 

 


 

npm 사용하지 않을 경우 Error 내용

더보기

 ERROR  Failed to compile with 1 error 

Failed to resolve loader: sass-loader
You may need to install it.
ERROR in ./src/App.vue 4:0-63
Module not found: Error: Can't resolve 'sass-loader' in ~~~

 

반응형
반응형

vue-router 바로가기

 

npm install

$ npm install vue-router

 

router.js

import { createRouter, createWebHistory } from "vue-router"

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      name : 'main',
      path: "/",
      component: () => import("@/pages/MainPage.vue"),
      meta: {
        requiresAuth: true
      }
    },
  ],

})

router.beforeEach(async (to, from, next) => {
  next()
})

export default router

 

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from '@/js/router'

const app = createApp(App)
app.use(router).mount('#app')

 

App.vue

<template>
  <router-view />
</template>

 

src/pages/MainPage.vue

<script setup>
import { } from 'vue'

</script>

<template>
  <section id="main_page">
    ㅁ메인페이지
  </section>
</template>

<style scoped lang='scss'>

</style>

 

반응형
반응형
import { getFirestore } from "firebase/firestore";

import { collection, getDocs } from "firebase/firestore";

const db = getFirestore(app);

const user = ref([])

onMounted(async () => {

    const querySnapshot = await getDocs(collection(db, "users"))

    let loginData = []
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data())
      
      loginData.push(doc.data())
    }
    
    user.value = loginData
    
})

 

반응형
반응형

Vue.JS 공식문서 바로가기

 

보통 vue에서 높이값을 구할때는 this.$refs를 사용하면 간단하게 값을 구할 수 있습니다.

그런데 v-if로 내용을 새로 추가하게 되었을 때는 this.$refs를 사용하면 undefined로 반환합니다.

이럴 때 this.$nextTick(() => {})를 사용합니다.

 

this.$nextTick(() => {}) ?

Vue가 데이터 변경 후, DOM 업데이트를 마칠 때까지 기다리려면 데이터가 변경된 직후 this.$nextTick(콜백)을 사용할 수 있습니다.

콜백은 DOM이 업데이트 된 후에 호출됩니다.

 

.vue ( html )

<div class="list" v-if="list">
    // '제목입니다'의 height값을 구하기 위한 내용입니다.
    <div id="list_title" class="list_title" ref="list_height">제목입니다.</div>
</div>

<button @click="btn()">리스트 보기</button>

 

.vue ( script )

methods: {
    btn() {
        this.list = true;
        this.$nextTick(() => {
            let height = this.$refs.list_height.clientHeight;
            
            let listHeight = document.getElementById("list_title");
            
            listHeight.style.height = `${height}px`;
        })
    }
}
반응형
반응형

예시 : dayjs 가져오기

 

dayjs.js

import dayjs  from 'dayjs'
import 'dayjs/locale/ko'
import relativeTime from 'dayjs/plugin/relativeTime'

dayjs.locale('ko')
dayjs.extend(relativeTime)

export default dayjs

 

main.js

import { createApp } from 'vue'
import App from './App.vue'
import dayjs from '@/assets/js/dayjs'


const app = createApp(App)

app.config.globalProperties.$dayjs = dayjs

app.mount('#app')

 

.vue

<script>
export default {
    data() {
        console.log(this.$dayjs(new Date()))
    }
}
</script>

 

반응형

+ Recent posts