Skip to content

26 - 实现简易版v-model指令 #1319

Open
@codelo-99

Description

@codelo-99
<script setup lang='ts'>

import { ref, defineExpose, toRef, watchEffect } from "vue"

/**
 * Implement a custom directive
 * Create a two-way binding on a form input element
 *
*/
const VOhModel = {
  mounted(el,binding,vnode,prevVnode){
    const arg = binding.arg
    const instanceModelRef = toRef(binding.instance, arg)
    el.$unwatch = watchEffect(()=>{
      el.value = instanceModelRef.value
    })
    el.$onInput = function(event){
      instanceModelRef.value = event.target.value
    }
    el.addEventListener('input',el.$onInput)
  },
  unmounted(el,binding,vnode,prevVnode){
    el.$unwatch()
    delete el.$unwatch
    el.removeEventListener('input',el.$onInput)
    delete el.$onInput
  }
}

const value = ref("Hello Vue.js")
const value2 = ref('1234')
defineExpose({
  value,
  value2,
})
</script>

<template>
  <p>
    <label>value:</label><input v-oh-model:value type="text" />{{ value }}
  </p>
  <p>
    <label>value:</label><input v-oh-model:value2 type="text" />{{ value2 }}
  </p>
</template>

Vue SFC Playground 在线链接

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions