vue2 data 一定要是函数吗?

答:不一定,可以是对象,vue文档中表述有误导性而已,他自己的例子里也有对象的形式


function initData(vm){

  let data = vm.$options.data

  data = vm._data = typeof data === ‘function’ ? getData(data, vm) : data || {}
   /*

     Because here,data is a reference from vm.$options.data, 
     if data is an object, 
     when there are many instances of this Component,
     they all use the same `data`


      if data is a function, Vue will use method getData( a wrapper to executing data function, adds some error handling)

      and return a new object, this object just belongs to current vm you are initializing

    */

   ……


  // observing data
  observe(data, true)

}

内容来自:https://stackoverflow.com/a/61184547/17160403

posted @ 2023-02-11 19:24  dou_fu_gan  阅读(23)  评论(0编辑  收藏  举报