自定义指令模拟v-model

412 阅读1分钟

钩子函数

指令

钩子函数的参数

指令

模拟实现

Vue.directive('mymodel', {
  bind: function(el, binding, vnode) {
    const vm = vnode.context
    const { value, expression } = binding
    el.value = value
    el.addEventListener('input', e => {
      vm[expression] = e.target.value
    })
  },
  // 当数据被更新的时候,需要更新指令绑定的元素
  update: function(el, binding) {
    const { value } = binding
    el.value = value
  }
})