Не удается установить свойство 'currentStatus' из неопределенного, используя "this" - PullRequest
0 голосов
/ 13 мая 2019

Я пытаюсь показать состояние formSubmit в vue js.Проблема в том, что я не очень знаком с использованием "this", и теперь я получаю сообщение об ошибке в некоторых местах кода, когда пытаюсь определить состояние с помощью "this.currentStatus".

Это мой код:

  const STATUS_INITIAL = 0
  const STATUS_SAVING = 1
  const STATUS_SUCCESS = 2
  const STATUS_FAILED = 3
 export default {
    name: 'Dashboard',
    data () {
      return {
        file: '',
        uploadError: null,
        currentStatus: null,
        uploadFieldName: 'photos'
      }
    },
    computed: {
      clientId () {
        return parseInt(this.$route.params.id)
      },
      isInitial () {
        return this.currentStatus === STATUS_INITIAL
      },
      isSaving () {
        return this.currentStatus === STATUS_SAVING
      },
      isSuccess () {
        return this.currentStatus === STATUS_SUCCESS
      },
      isFailed () {
        return this.currentStatus === STATUS_FAILED
      }
    },
    methods: {
      handleFileUpload () {
        this.file = this.$refs.file.files[0]
        console.log(this.file)
      },
      filesChange (fieldName, fileList) {
        // handle file changes
        const formData = new FormData()

        // append the files to FormData
        Array
          .from(Array(fileList.length).keys())
          .map(x => {
            formData.append(fieldName, fileList[x], fileList[x].name)
          })

        // save it
        this.submitFile(formData)
      },
      submitFile (formData) {
        this.currentStatus = STATUS_SAVING
        console.log(this.currentStatus)
        var clientId = this.clientId
        var reader = new FileReader()
        reader.readAsDataURL(this.file)
        reader.onload = function () {
          var asim = reader.result
          formData.append('file', this.file)
          let promises = []
          promises.push(
            performRpcWithPromise('insertContract', [
              asim, clientId
            ]).then(function (res) {
              console.log(res)
              this.currentStatus = STATUS_SUCCESS
              console.log(this.currentStatus)
            })
          )
        }
      }
    }
  }

И это моя форма:

<p v-if="isSuccess">
              DONE
            </p>
            {{currentStatus}}
            <form enctype="multipart/form-data" novalidate>
            <input type="file" placeholder="Velg en fil" id="file" ref="file" v-on:change="handleFileUpload()"
                   accept="application/pdf" class="input-file" @change="filesChange($event.target.name, $event.target.files); fileCount = $event.target.files.length">
              <p v-if="isSuccess">
                wow
              </p>
              <p v-if="isSaving">
              Uploading {{ fileCount }} files...
            </p>
            </form>

Я следовал этому руководству Ошибкая получаю вот эту строку: (внутри обещания)

this.currentStatus = STATUS_SUCCESS

Это немного странно для меня, потому что this.currentStatus = STATUS_SAVING работает и показывает число «1», но не внутриобещание (.then).

Кто-нибудь может понять, почему это работает не внутри обещания, а снаружи?

Ответы [ 2 ]

3 голосов
/ 13 мая 2019

Попробуйте вместо этого использовать функцию стрелки. Как это:

.then(res => {
  console.log(res)
  this.currentStatus = STATUS_SUCCESS
  console.log(this.currentStatus)
})

Я считаю, что это похоже на это .

1 голос
/ 13 мая 2019

Вы можете использовать функцию стрелки или замыкание:

var self = this
reader.onload = function () {
  var asim = reader.result
  formData.append('file', self.file)
  let promises = []
  promises.push(
    performRpcWithPromise('insertContract', [
      asim, clientId
    ]).then(function (res) {
      console.log(res)
      self.currentStatus = STATUS_SUCCESS
      console.log(self.currentStatus)
    })
  )
}

Если вы хотите использовать функцию стрелки, попробуйте

reader.onload = () => {
  var asim = reader.result
  formData.append('file', this.file)
  let promises = []
  promises.push(
    performRpcWithPromise('insertContract', [
      asim, clientId
    ]).then((res) => {
      console.log(res)
      this.currentStatus = STATUS_SUCCESS
      console.log(this.currentStatus)
    })
  )
}
...