개발은 재밌어야 한다
article thumbnail
반응형

Vue에서 text파일 .txt로 저장하고 text로된 .txt파일을 불러와서 Vue의 data영역의 데이터에 바인딩을 하기 위해 만든 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<template>
  <div style="height:100px;">
    <!-- txt 파일 불러오기 버튼 -->
    <button @click="importTextFile">불러오기</button>
    <!-- txt 파일 저장하기 버튼 -->
    <button @click="exportTextFile">저장</button>
    <br>
    <!-- text 영역-->
    <textarea id="text-data" v-model="textData" rows="8" cols="100"></textarea>
  </div>
</template>
 
<script>
export default {
  name'TextFile',
  data() {
    return {
      /**
       * textarea에 보여줄 텍스트
       * @type {String}
       */
      textData: '',
    };
  },
  methods: {
    /**
     * txt파일을 불러온다
     */
    importTextFile() {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'text/plain'// 확장자가 xxx, yyy 일때, ".xxx, .yyy"
      // this 접근을 위해 선언 필요
      const self = this;
      input.onchange = function () {
        const file = new FileReader();
        file.onload = () => {
          document.getElementById('text-data').textContent = file.result;
          self.$data.textData = file.result;
        };
        file.readAsText(this.files[0]);
      };
      input.click();
    },
    /**
     * textData를 txt 파일로 저장한다.
     */
    exportTextFile() {
      const text = document.getElementById('text-data').value;
      // 저장하고자하는 파일명
      const filename = '텍스트파일명';
      const element = document.createElement('a');
      element.setAttribute('href''data:text/plain;charset=utf-8, ' + encodeURIComponent(text));
      element.setAttribute('download', filename);
      document.body.appendChild(element);
      element.click();
    },
  },
};
</script>
<style lang="scss" scoped></style>
 
cs

불러오기를 누르면 txt파일을 불러와 textarea에 바인딩
지정한 파일명으로 저장됩니다

불러올 .txt도 만들어서 테스트 해봅니다.

임의 생성한 테스트 .txt
잘 바인딩됩니다

스타일 적인 부분들 제외하고 Vue에서 javascript로 Vue의 v-model에 바인딩되어 있는 데이터를 .txt로 바인딩 하기 위한 코드로 참고 해주시면 될 것 같습니다.

 

 

 

 

 

 

참고

https://www.delftstack.com/ko/howto/javascript/javascript-download/

 

JavaScript를 사용하여 파일 다운로드

이 튜토리얼에서는 JavaScript를 사용하여 파일을 다운로드하는 방법을 설명합니다.

www.delftstack.com

http://www.gisdeveloper.co.kr/?p=5566 

 

웹에서 Javascript 만으로 텍스트 파일 읽기 – GIS Developer

웹에서 JS 언어만으로 로컬에 저장된 텍스트 파일을 읽어 오는 코드를 정리한 글이다. 먼저 아래는 예제 코드 실행을 위한 DOM 구성에 대한 코드이다. Open ... Open 버튼을 클릭하면 텍스트 파일을

www.gisdeveloper.co.kr

 

반응형

'javascript > Vue' 카테고리의 다른 글

[Vue] 배열 데이터가 Rerendering 안되는 현상  (0) 2021.11.22
[Vue] Swiper 미적용 해결 및 사용기  (0) 2021.08.19
Font Awesome 사용하기  (0) 2021.08.02
profile

개발은 재밌어야 한다

@ghyeong

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!