Home  >  Q&A  >  body text

javascript - About data binding in Vue

Vue's official documentation says that the data of the Vue instance is stored in the data object, and Vue will recursively convert the properties of data into getters/setters, so that the properties of data can respond to data changes.

var data = { a: 1 }
// 直接创建一个实例
var vm = new Vue({
  data: data
})
vm.a // -> 1
vm.$data === data // -> true

My question now is:

data() {
      return {
        favorite: (() => {
            return loadFromLocal(this.seller.id, 'favorite', false);
        })()
      };
    }

LoadFromLocal is a function declared globally. The Vue instance converts the properties in the data into getters and setters. The return value of this immediately executed function will change due to changes in other functions. How does Vue monitor data changes when I call favorite's getter and setter without explicitly calling it? Is it to check the return value of the immediately executed function every once in a while?

怪我咯怪我咯2734 days ago661

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:34:29

    1. The immediate execution function has been executed before new Vue

    var App = {
      data() {
        return {
          a: (()=>{ return 1; })()
        }
      }
    }
    
    new Vue({App});

    2. Monitoring is done through getters and setters, nothing before.
    Printing attributes in the template and accessing attributes when ready are equivalent to calling getters

    reply
    0
  • 为情所困

    为情所困2017-05-19 10:34:29

    data() {
          return {
            favorite: (() => {
                return loadFromLocal(this.seller.id, 'favorite', false);
            })()
            //其实和下面没区别,只是初始赋值是立即执行函数的返回值而已
            favorite:1
          };
        }

    reply
    0
  • Cancelreply