API 用法:
vue.set( target, key, value )
参数:
- {
- Object | Array
- } target
- {
- string | number
- } key
- {
- any
- } value
返回值: 设置的值.
用法:
为响应式对象添加一个属性, 确保新属性也是响应式的, 并且能够触发视图更新. 这必须用于为响应式对象添加新属性, 因为 Vue 无法检测到普通属性的添加 (例如, this.myObject.newProperty = 'hi').
target 对象不能是 Vue 实例, 或者 Vue 实例的根数据对象.
需求:
发送请求之后, 立即禁用按钮, 五秒之后, 恢复按钮, 目的是防止按钮多次被点击
最开始是这样来改变当前按钮的状态的, 但是一直没生效, 后面百度了很久才知道是因为, vulData 这个对象本来没有 isDisabled 这个属性, 所以即使在最开始添加了以下代码, 来给它赋值, 后面也无法改变它的状态;
this.vulData[index].isDisabled = false;
后面看到关于 $set 的用法, 尝试了一下, 发现可以起作用
代码:
- API.vulIgnore(parseInt(id), status).then((response) => {
- // 禁用按钮
- this.$set(this.vulData[index], 'isDisabled', true)
- let res = response.data;
- if (res.code == 0) {
- this.$message({
- message: '操作成功',
- showClose: true,
- type: 'success'
- })
- this.vulData[index].status = res.data.status;
- // 5 秒之后启用按钮
- setTimeout(() => {
- this.$set(this.vulData[index], 'isDisabled', false)
- }, 5000)
- this.$set(this.vulData[index], 'isDisabled', true)
- } else {
- this.$message({
- message: res.message,
- showClose: true,
- type: 'error'
- })
- this.$set(this.vulData[index], 'isDisabled', false)
- }
- })
来源: http://www.qdfuns.com/note/46360/8e96ad1f36f61d22928cd9768e87afc9.html