【问题标题】:can not read/write data in function无法在函数中读取/写入数据
【发布时间】:2019-07-13 06:37:56
【问题描述】:

您好,我使用 vue 和 axios 上传文件

无法识别 onUploadProgress 里面的列表

代码

data: ()=>({
        list: [
          { id:0, icon: 'image', iconClass: 'blue white--text', title: 'Vacation itinerary', file:"asasf.png", progress:100 },
          selectedFile: null
        ]
    }),
    methods:{
        async startUpload(){
            let formData = await new FormData();
            await formData.append('file', this.selectedFile);
            this.selectedFile=null

            let config = {
                onUploadProgress: function(progressEvent){
                    console.log(this.list) //is null
                    this.list[id].progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
                }
            };

            this.$axios.$post('/upload/insert', formData, config)
                .then(response => {
                    this.list[id].progress=100
                    this.list[id].file=response.data.path
                })
                .catch(error => {
                    console.log(error)
                })
        }
    }

console.log(this.list) in lone 16 为空

【问题讨论】:

    标签: vue.js axios nuxt.js


    【解决方案1】:

    只需将onUploadProgress函数改为箭头函数即可,否则this将关联到onUploadProgress的上下文而不是组件。

    async startUpload(){
                let formData = await new FormData();
                await formData.append('file', this.selectedFile);
                this.selectedFile=null
    
                let config = {
                    onUploadProgress: (progressEvent) => {
                        console.log(this.list) //is null
                        this.list[id].progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
                    }
                };
    
                this.$axios.$post('/upload/insert', formData, config)
                    .then(response => {
                        this.list[id].progress=100
                        this.list[id].file=response.data.path
                    })
                    .catch(error => {
                        console.log(error)
                    })
            }

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2023-02-13
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多