添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
博学的领带  ·  05-18 17:26:04.728 ...·  3 月前    · 
狂野的炒饭  ·  SQL过关 - 吴秦 - 博客园·  4 月前    · 
温柔的沙滩裤  ·  javascript - Mapping ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

So I am trying to store JSON data in a variable in a Vue project.

The code to upload and store the file is

<input type="file" id="file" ref="fileSelect" class="custom-file-input" @change="showfiles" />

<script lang="ts">
methods: {
showfiles() {
    let files = this.$refs.fileSelect.files //Error Object is of type 'unknown'. ts(2571) 
    var reader = new FileReader();
    reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
    reader.readAsText(files[0]);
    console.log(this.p) //I am storing JSON data in p

I searched online and found various fixes but none of them are working for me I tried adding "useUnknownInCatchVariables": false to tsconfig, it fixes the error momentarily but the error comes back. I also tried try and catch

showfiles() {
        let files = this.$refs.fileSelect.files
        var reader = new FileReader();
        reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
        reader.readAsText(files[0]);
        console.log(this.p)
      catch(err) {
        if (err instanceof Error) { 
      console.log(err.message);
    } else {
      console.log('Unexpected error', err);

But none of these worked. I'll greatly appreciate any suggestion.

Try to cast the type of fileSelect ref yourself like that:

showfiles() {
  const files = (this.$refs.fileSelect as HTMLInputElement).files // const files: FileList | null
    // ...

I guess you are not reading the result correctly. According to MDN you should just take the result from filereader's result property.

reader.addEventListener("load", () => {
  this.p = JSON.parse(reader.result);
}, false);
                Now I am getting an error in the next lines reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); }; Property 'result' does not exist on type 'FileReader | null'.ts(2339) and in line reader.readAsText(files[0]); Object is possibly 'null'.ts(2531)
– harsh panday
                Jun 2, 2022 at 6:29
                Try to access the result like that: reader.onload = () => { this.p = JSON.parse(reader.result); }
– Eduardo
                Jun 2, 2022 at 6:55
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.