特性

var app = Vue.createApp({
  data() {
    return {
      title: 'This is my TITLE'
    }
  },
  template: `
    <h1>{{ title }}</h1>
    <button @click="changeTitle">CHANGE TITLE</button>
  `,
  methods: {
    changeTitle() {
      this.title = 'This is your TITLE'
    }
  }
});

const vm = app.mount('#app');

方法挂载在实例上

而不是 methods 上,而且也没抛出 methods 属性到 vm 实例上

var app = Vue.createApp({
  data() {
    return {
      title: 'This is my TITLE'
    }
  },
  template: `
    <h1>{{ title }}</h1>
    <button @click="changeTitle('This is your TITLE')">CHANGE TITLE</button>
  `,
  methods: {
    changeTitle(title) {
      this.title = title;
    }
  }
});

const vm = app.mount('#app');
console.log(vm);
console.log(vm); // undefined

Untitled

lodash 的 debounce 防抖函数

第一种写法:

组件共用一个debounce,每个实例都共用它,不太好

Untitled

第二种写法(推荐):

每次创建的时候都返回一个新的debounce函数

Untitled

手写data

var Vue = (function() {
  function Vue(options) {
    this.$data = options.data();
    this._methods = options.methods;

    this._init(this);
  }

  Vue.prototype._init = function(vm) {
    initData(vm);
    initMethods(vm);
  }

  function initData(vm) {
    for (var key in vm.$data) {
      (function(k) {
        Object.defineProperty(vm, k, {
          get: function() {
            return vm.$data[k];
          },
          set: function(newVal) {
            vm.$data[k] = newVal;
          }
        });
      })(key);
    }
  }

  function initMethods(vm) {
    for (var key in vm._methods) {
      vm[key] = vm._methods[key];
    }
  }

  return Vue;
})();

var vm = new Vue({
  data() {
    return {
      a: 1,
      b: 2
    }
  },
  methods: {
    increaseA(num) {
      this.a += num;
    },
    increaseB(num) {
      this.b += num;
    },
    getTotal() {
      console.log(this.a + this.b);
    }
  }
});

vm.increaseA(1);
vm.increaseA(1);
vm.increaseA(1);
vm.increaseA(1); // 5

vm.increaseB(2);
vm.increaseB(2);
vm.increaseB(2);
vm.increaseB(2); // 10

vm.getTotal(); // 15