$set()的正确使用方式
vue给对象新增属性,并触发视图更新
如下代码:给student对象新增age属性
data () {
return {
student: {
name: '',
sex: ''
}
}
}
众所周知,直接给student赋值操作,虽然可以新增属性,但是不会触发视图更新
mounted () {
this.student.age = 24
}
原因是:受 ES5 的限制,Vue.js 不能检测到对象属性的添加或删除。因为 Vue.js 在初始化实例时将属性转为 getter/setter,所以属性必须在 data 对象上才能让 Vue.js 转换它,才能让它是响应的。
要处理这种情况,我们可以使用$set()方法,既可以新增属性,又可以触发视图更新。
但是,值得注意的是,网上一些资料写的$set()用法存在一些问题,导致在新接触这个方法的时候会走一些弯路
错误写法:this.$set(key,value)
mounted () {
this.$set(this.student.age, 24)
}
正确写法:this.$set(this.data,”key”,value’)
mounted () {
this.$set(this.student,"age", 24)
}
项目实例
updateTimeformat (val, index) {
let time = val
let d = new Date(time)
this.updateTimeArr[index] = formatDate(d, 'yyyy-MM-dd hh:mm:ss');
this.$set(this.updateTimeArr, index, this.updateTimeArr[index]);
},
随机推荐
- Oracle课程档案,第一天。
sys是Oracle最高权限者 DBSNMP:简单网络管理系统 ctrl+d回到oracle目录 在SQL中输入 exit也可以 select:列 where:行 sqlplus / as sysdb ...
- javascript的数组之find()
find()方法返回数组中第一个满足回调函数测试的第一个元素的值.否则返回undefined const arr1 = [1, 2, 3, 4, 6, 9]; let found = arr1.fin ...
- WPS生成文章目录
WPS生成文章目录 1.引用–>插入目录...即可!
- Web开发——HTML基础(高级文本格式 列表/style)
文档资料参考: 参考:https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_fo ...
- Windows10远程桌面Ubuntu16.04
一.Ubuntu16.04端软件安装(管理员权限) 1.安装xrdp sudo apt-get install xrdp 2.安装vnc4server sudo apt-get install vnc ...
- threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/dyuproject/protostuff/MapSchema$MessageFactory] with root cause
错误记录 前几天朋友问我一个错误,顺便记录一下,关于redis 工具类,protostuff序列化报错. threw exception [Handler processing failed; nes ...
- bugfree3.0.1-邮件配置
系统内新建BUG或Case,或者BUG状态有修改时,这些操作都可以伴随邮件通知,提醒指派和抄送给对象及时关注. 配置方法 1.进入C:\xampp\htdocs\bugfree\protected\c ...
- python基础(11)-常用模块
re(正则)模块 常用方法 findall() 以列表返回所有满足条件的结果 import re print(re.findall('\d','a1b2c2abc123'))#['1', '2', ' ...
- vue-cli 搭建的项目,无法用本地IP访问
项目是用vue-cli搭建的,是基于移动端的,需要在手机上测试的时候发现用ip访问不了,用localhost是可以访问的,网上查资料的解决办法(此为Mac机子的解决办法): 在config文件里面的i ...
- [py]GTM和UTC及python的时间戳
时间戳是一串字符串 time.time() 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总毫秒数.通俗的讲, 时间戳是一 ...