javascript - 无法使用“this”设置未定义的属性“currentStatus”
问题描述
我试图在 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>
我遵循了本指南 我得到的错误是这一行:(在承诺内)
this.currentStatus = STATUS_SUCCESS
这对我来说有点奇怪,因为this.currentStatus = STATUS_SAVING
它正在工作并显示数字“1”,但不在承诺(.then)内。
任何人都可以看到为什么这在承诺内部而不是在外部起作用?
解决方案
尝试使用箭头函数。像这样:
.then(res => {
console.log(res)
this.currentStatus = STATUS_SUCCESS
console.log(this.currentStatus)
})
我相信它与此类似。
推荐阅读
- scala - 数据库中的火花存储作业进度详细信息
- java - 如何限制用户在java中输入4位密码
- mysql - 如何从表中拆分数据并插入新关系?
- mysql - MySQL,使用带有子查询的索引
- ruby-on-rails - “exec_query”是否需要“with_connection”?
- javascript - 将角形分割成多个部分
- asp.net - 我可以调用 Web 服务但无法从 WEB SERVICE 获得响应
- java - 在泛型类的静态类中使用泛型类型
- excel - 在受保护的工作表上启用宏按钮 - Excel
- java - 我在 Spring Boot 中运行 shell 命令,但 process = Runtime.getRuntime().exec(cmd) 不运行