Vue进阶(九十八):Vue

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)

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值