Vue2.x源码:data初始化

vue初始化数据

var app = new Vue({
  data() {
    return {
      msg: 'hello,weekend!',
      name: 'YanHSama'
    }
  },
  mounted() {
    console.log('vue', this);
  },
  watch: {
  },

  computed: {
  },
  methods: {
  },
})
// mount
app.$mount('#testdata')

在这里插入图片描述

proxy代理
在这里插入图片描述

数据代理

在Vue初始化时,执行_init方法,_init函数汇总会执行initData方法

function initData (vm: Component) {
  let data = vm.$options.data
  //赋值vm._data
  data = vm._data = typeof data === 'function'? getData(data, vm) : data || {}

  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]

    if (props && hasOwn(props, key)) {
//给出警告,data存在key与props的key同名
    } else if (!isReserved(key)) {
      // 当key 不已$ or _开头,进行代理
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  //对数据进行观测 --响应式数据核心
  observe(data, true /* asRootData */)
}

//执行data方法
export function getData (data: Function, vm: Component): any {
//加入栈
  pushTarget()
  try {
  //执行data方法,this指向vm
    return data.call(vm, vm)
  } catch (e) {
    handleError(e, vm, `data()`)
    return {}
  } finally {
  //移除栈
    popTarget()
  }
}
Dep.target = null
const targetStack = []

export function pushTarget (target: ?Watcher) {
  targetStack.push(target)
  Dep.target = target
}

export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

代理

export function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}
const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}

export function observe (value: any, asRootData: ?boolean): Observer | void {
//判断是否对象或者是否vnode,如果不是不做检测
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  //判断value是否含有__ob__属性,这是标明是否已经被检测的标志
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
  //shouldObserve默认值为true
    shouldObserve &&
    //是否服务端渲染
    !isServerRendering() &&
    //是否数组,是否对象,是否可扩展
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}


在这里插入图片描述

Observer类

export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that has this object as root $data

  constructor (value: any) {
    // this为Observe
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
//给value新增一个__ob__属性,值为该value的Observer实例,相当于为value打上标记,表示它已经被转化成响应式了,避免重复操作
    def(value, '__ob__', this)
//判断是否数组
    if (Array.isArray(value)) {
      const augment = hasProto ? protoAugment : copyAugment
      augment(value, arrayMethods, arrayKeys)
      this.observeArray(value)
    } else {
//只有object类型的数据才会调用walk将每一个属性转换成getter/setter的形式来侦测变化
      this.walk(value)
    }
  }

  /**
   * Walk through each property and convert them into
   * getter/setters. This method should only be called when
   * value type is Object.
   */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i], obj[keys[i]])
    }
  }

  /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      // 对数组数据类型进行深层观测
      observe(items[i])
    }
  }
}


export function defineReactive (
  obj: Object,//obj 对象
  key: string,//对象的key
  val: any,//对象的某个key的值
  customSetter?: ?Function,
  shallow?: boolean
) {
//实例化一个依赖管理器,生成一个依赖管理数组dep
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
  //如果只传了obj和key,那么val = obj[key]
    val = obj[key]
  }

  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      if (Dep.target) {
       在getter中收集依赖
        dep.depend()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // #7981: for accessor properties without setter
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      //在setter中通知依赖更新
      dep.notify()
    }
  })
}


Dep类


export default class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array<Watcher>;

  constructor () {
    this.id = uid++
    //初始化了一个subs数组,用来存放依赖
    this.subs = []
  }

  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

//移除一个依赖
  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }
//添加一个依赖
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

// 通知所有依赖更新
  notify () {
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于Vue3可视化Echarts图的源码可以通过以下步骤实现: 1. 引入echarts库:首先,在Vue3项目中安装echarts库。可以通过在终端中运行`npm install echarts --save`命令来安装echarts。然后,在需要使用可视化图的Vue组件中,引入echarts库:`import echarts from 'echarts'`。 2. 创建图表容器:在Vue组件的模板中,创建一个容器元素,用于承载echarts图表。例如,可以在模板中添加一个`<div id="chartContainer"></div>`。 3. 初始化图表实例:在Vue组件中的`mounted`生命周期钩子函数中,初始化echarts图表实例。首先,获取图表容器的DOM元素:`const chart = document.getElementById('chartContainer')`。然后,创建echarts实例:`const myChart = echarts.init(chart)`。 4. 配置图表选项:使用echarts实例的`setOption`方法,配置图表的选项。例如,可以设置图表的类型、标题、x轴和y轴等:`myChart.setOption({ type: 'bar', title: { text: '柱状图' }, xAxis: { data: ['A', 'B', 'C'] }, yAxis: {} })`。 5. 绑定数据:将需要的数据绑定到图表中。可以通过Vue组件的props属性传递数据,或者通过axios等方式请求后端API获取数据,并将数据传递给图表实例的`setOption`方法。 6. 更新图表:在数据变化时,更新图表的显示。可以通过Vue组件的watch属性监听数据变化,并在数据变化后,调用图表实例的`setOption`方法更新图表。 7. 销毁实例:在Vue组件的`beforeUnmount`生命周期钩子函数中,调用echarts实例的`dispose`方法销毁图表实例。 通过以上步骤,我们可以基于Vue3实现echarts可视化图的源码。这样,我们可以根据实际需求,灵活地配置和更新图表,实现丰富的可视化效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值