我正在尝试在vue js中显示formSubmit的状态。问题是我对使用"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>
I followed this guide 我得到的错误是这一行:(在承诺内)
this.currentStatus = STATUS_SUCCESS
这对我来说有点奇怪,因为this.currentStatus = STATUS_SAVING
正在工作并显示数字“ 1”,但不在承诺(.then)内。
任何人都可以看到为什么这不是在诺言中起作用,而是在诺言之外吗?
答案 0 :(得分:3)
尝试改用箭头功能。像这样:
.then(res => {
console.log(res)
this.currentStatus = STATUS_SUCCESS
console.log(this.currentStatus)
})
我相信它类似于this。
答案 1 :(得分:1)
您可以使用箭头功能或闭包:
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)
})
)
}