mounted () {
this.$set(this.student,"age", 24)
}
Vue
不允许动态添加根级响应式属性。
例如:
const app = new Vue({
data: {
a: 1
}
// render: h => h(Suduko)
}).$mount('#app1')
Vue.set(app.data, 'b', 2)
此时控制台会报错:
只可以使用 Vue.set(object, propertyName, value)
方法向嵌套对象添加响应式属性,例如
var vm=new Vue({
el:'#test',
data:{
//data中已经存在info根属性
info:{
name:'小明';
}
}
});
//给info添加一个性别属性
Vue.set(vm.info,'sex','男');
有童鞋可能会问之前使用过Vue.set()
,this.$set()
与Vue.set
有什么联系呢?
三、Vue.set() 和 this.$set() 实现原理
源码分析
先来看看Vue.set()
源码:
import { set } from '../observer/index'
...
Vue.set = set
...
再看看this.$set()
源码:
import { set } from '../observer/index'
...
Vue.prototype.$set = set
...
我们发现Vue.set
()和this.$set()
这两个api
的实现原理基本一模一样,都使用了set()
。set()
函数是从 ../observer/index
文件中导出的,区别在于:Vue.set()
是将set
函数绑定在Vue
构造函数上,this.$set()
将set
函数绑定在Vue
原型上。
再来看下set
源码:
function set (target: Array<any> | Object, key: any, val: any): any {
if (process.env.NODE_ENV !== 'production' &&
(isUndef(target) || isPrimitive(target))
) {
warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val
return val
}
const ob = (target: any).__ob__
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return val
}
if (!ob) {
target[key] = val
return val
}
### 结尾
学习html5、css、javascript这些基础知识,学习的渠道很多,就不多说了,例如,一些其他的优秀博客。但是本人觉得看书也很必要,可以节省很多时间,常见的javascript的书,例如:javascript的高级程序设计,是每位前端工程师必不可少的一本书,边看边用,了解js的一些基本知识,基本上很全面了,如果有时间可以读一些,js性能相关的书籍,以及设计者模式,在实践中都会用的到。
![html5](https://img-blog.csdnimg.cn/img_convert/d35c2cf2d5364b4907e65f1856c923a4.png)