In my attempt to display the state of formSubmit in vue js, I've encountered an issue. My lack of familiarity with using "this" has led to errors in the code, particularly when trying to indicate the status using "this.currentStatus".
This is the code snippet:
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)
})
)
}
}
}
}
This is how the form looks like:
<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>
I followed this guide The error occurs on this line: (inside the promise)
this.currentStatus = STATUS_SUCCESS
It's perplexing to me that while
this.currentStatus = STATUS_SAVING
works and displays "1", it doesn't work inside the promise (.then).
If anyone can pinpoint why this works outside the promise but not within, I'd greatly appreciate the insight.