Why must vue component data be a function?

后端 未结 4 2010
感动是毒
感动是毒 2020-12-31 02:55

I am reading up on Vue components, and find their explanation of why data needs to be a function somewhat confusing:

The root instance



        
4条回答
  •  梦谈多话
    2020-12-31 03:57

    Because when Vue init data,

    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)
    
    }
    
    

提交回复
热议问题