728x90

firebase 와 연동중이라면 vue3 에서 파일을 업로드 하고 다운로드 링크를 추출 하는 예제 이다. 이렇게 구현하면 백엔드 없이도 파일 업로드 구현이 가능하다. 

<template>
  <div>
    <input type="file" ref="fileInput" @change="uploadFile" />
    <progress v-if="uploading" :value="uploadProgress"></progress>
    <div v-if="downloadURL">
      <p>파일이 성공적으로 업로드되었습니다.</p>
      <a :href="downloadURL" download>다운로드 링크</a>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { getStorage, ref as storageRef, uploadBytes, getDownloadURL } from 'firebase/storage'

const fileInput = ref(null)
const uploading = ref(false)
const uploadProgress = ref(0)
const downloadURL = ref(null)
const fileRef = ref(null)

const storage = getStorage() // Firebase Storage 초기화

const uploadFile = async () => {
  if (!fileInput.value.files.length) {
    return
  }

  const file = fileInput.value.files[0]
  const storageReference = storageRef(storage, 'uploads/' + file.name)

  try {
    uploading.value = true

    // 파일 업로드
    const snapshot = await uploadBytes(storageReference, file, (snapshot) => {
      uploadProgress.value = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
    })
    
    //파일 다운로드 전체 링크 저장
     fileRef.value = snapshot.ref.fullPath;

    // 파일 다운로드 URL 가져오기
    downloadURL.value = await getDownloadURL(snapshot.ref)
  } catch (error) {
    console.error('파일 업로드 중 오류 발생:', error)
  } finally {
    uploading.value = false
  }
}
</script>
728x90
728x90

localStorage 

json data (SET, GET)

localStorage.setItem('SET_MENU_ALL', JSON.stringify(treeMenu));

const storedData = JSON.parse(localStorage.getItem('treeMenu'));

 

SET, GET

localStorage.setItem('SET_MENU_ALL', treeMenu);

const storedData = localStorage.getItem('treeMenu');

 

Delete

localStorage.removeItem('SET_MENU_ALL')

 

sessionStorage (브라우저 끄면 사라짐)

sessionStorage.setItem('SET_MENU_ALL', treeMenu)

sessionStorage.getItem('SET_MENU_ALL')

sessionStorage.removeItem('SET_MENU_ALL')

728x90
728x90

<script>
export default {
  data() {
    return {
      myData: null
    }
  },
  beforeRouteEnter(to, from, next) {
    // API 호출
    axios.get('/api/my-data')
      .then(response => {
        // 데이터 저장
        next(vm => vm.myData = response.data)
      })
      .catch(error => {
        console.log(error)
      })
  }
}
</script>

 

beforeRouteEnter 로 router 를 타기전 호출 할수 있는 방법으로 

to 와 from 에는 아래와 같은 속성을 담고 있다. 

 

name: 현재 라우트의 이름
path: 현재 라우트의 경로
hash: URL의 해시 값
query: URL의 쿼리 파라미터 객체
params: URL의 동적 라우트 매개변수 객체
meta: 현재 라우트의 메타 데이터 객체

 

아래는 router 타기전 api 를 호출 하고 store 에 함수를 호출 하여 

값을 저장 하는 로직을 보여주고 있다. 

 

import store from '@/store'

export default {
  data() {
    return {
      myData: null
    }
  },
  beforeRouteEnter(to, from, next) {
    // API 호출
    axios.get('/api/my-data')
      .then(response => {
        // 데이터 저장
        store.commit('SET_MY_DATA', response.data)
        next()
      })
      .catch(error => {
        console.log(error)
      })
  }
}

728x90
728x90

싱글 파일 업로드 일 경우 

<template>
  <div>
    <v-file v-model="file" accept="image/*" @change="onFileChange" />
    <img v-if="previewImage" :src="previewImage" />
    <button @click="uploadFile" :disabled="!file">Upload</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null,
      previewImage: null,
    }
  },
  methods: {
    onFileChange() {
      if (this.file) {
        this.previewImage = URL.createObjectURL(this.file)
      } else {
        this.previewImage = null
      }
    },
    uploadFile() {
      const formData = new FormData()
      formData.append('file', this.file)

      // Make your API call to upload the file with the formData
      // ...
    }
  },
  beforeDestroy() {
    if (this.previewImage) {
      URL.revokeObjectURL(this.previewImage)
    }
  }
}
</script>

 

다중파일 업로드 일 경우

<template>
  <div>
    <v-file v-model="files" accept="image/*" multiple @change="onFileChange" />
    <div v-for="(preview, index) in previewImages" :key="index">
      <img :src="preview" />
    </div>
    <button @click="uploadFiles" :disabled="!files || !files.length">Upload</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      files: [],
      previewImages: [],
    }
  },
  methods: {
    onFileChange() {
      this.previewImages = []
      for (let i = 0; i < this.files.length; i++) {
        const file = this.files[i]
        if (file && file.type.startsWith('image/')) {
          this.previewImages.push(URL.createObjectURL(file))
        }
      }
    },
    uploadFiles() {
      const formData = new FormData()
      for (let i = 0; i < this.files.length; i++) {
        formData.append('files[]', this.files[i])
      }

      // Make your API call to upload the files with the formData
      // ...
    }
  },
  beforeDestroy() {
    for (let i = 0; i < this.previewImages.length; i++) {
      URL.revokeObjectURL(this.previewImages[i])
    }
  }
}
</script>

 

beforeDestroy 

beforeDestroy 는 라이프사이클 훅 중 하나로 

컴포넌트가 소멸 되기 직전에 호출된다. 

따라서 위 예제에서는 이미지 파일의 URL 을 삭제하는 역할을 한다.

728x90
728x90

git 에서 업데이트 후 해주면 잘 됨

 

git remote update
git fetch

git checkout 브랜치명

 

브랜치 이동 명령어는 git checkout 브랜치명

브랜치 생성 명령어는 git branch 브랜치명

브랜치 리스트 확인은 git branch

 

브랜치 삭제명령어는 

git branch -d 브랜치명

 

728x90
728x90

소스코드에서 바로 나누기 하는 방법

 

<ul>
  <li v-for="(item, index) in dataList" :key="index">
    {{ (item / 1024).toLocaleString() }}
  </li>
</ul>

 

computed 로 data 자체를 가공해서 노출 하는 방법

<ul>
  <li v-for="(item, index) in filteredDataList" :key="index">
    {{ item }}
  </li>
</ul>

 

computed: {
  filteredDataList() {
    return this.dataList.map(item => {
      return (item / 1024).toLocaleString();
    });
  },
},

728x90
728x90

Cannot read properties of undefined (reading 'dispatch')"

 

컴포넌트에서 store 호출이 안될때 

vuex 버전을 3로 낮추니까 해결 되었다. 

 

vue2 에서는 vuex 4 버전은 오류가 있는거 같다. 

 

yarn add vuex@3.0.0

 

 

728x90
728x90

yarn global add @vue/cli

 

vue --version 버전 확인

 

vue create front

 

vue2 default 선택
설치 후

cd front 

npm run serve 

실행 되는지 확인 

 

vue add vuetify

설치 후(default)

 

나는 안되서 vite vuetify 로 선택 하니 되었다. preview 이긴 하지만..

일단은 페이지 뜨는데는 성공 

 

 

 

728x90
728x90

rm -rf node_modules

rm -rf yarn.lock

728x90

'VUE' 카테고리의 다른 글

vue2 에서 vuex store 오류  (0) 2023.01.22
vue vuetify  (0) 2022.12.29
vue nuxt env 설정  (0) 2022.12.20
git 사용자 정보 저장 명령어  (0) 2022.12.20
vue vite vuex  (0) 2022.12.10
728x90

nuxt 에는 dotenv 설치가 되어 있기 때문에 추가 적으로 더 설치할 필요는 없다.

 

nuxt.config.js

require('dotenv').config();
  axios: {
    //baseURL: '/',
    baseURL: process.env.VUE_APP_GW_URL,
  },
  env: {
    VUE_APP_ATTACH_FILE_SERVER_URL : process.env.VUE_APP_ATTACH_FILE_SERVER_URL,
  },

package.json

"scripts": {
    "dev": "nuxt --dotenv .env.development",
    "build": "nuxt build --dotenv .env.production",
    "start": "nuxt start --dotenv .env.production",
    "generate": "nuxt generate",
    "lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
    "lint": "yarn lint:js",
    "test": "jest",
  },
728x90

'VUE' 카테고리의 다른 글

vue vuetify  (0) 2022.12.29
rm -rf node_modulesrm -rf yarn.lock 노드모듈 삭제 명령어  (0) 2022.12.20
git 사용자 정보 저장 명령어  (0) 2022.12.20
vue vite vuex  (0) 2022.12.10
react vite  (0) 2022.12.08

+ Recent posts