vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

26 - 实现简易版`v-model`指令

Open kalu5 opened this issue 2 years ago • 0 comments

// 你的答案
<script setup lang='ts'>

import { ref, Binding, unref } from "vue"

/**
 * Implement a custom directive
 * Create a two-way binding on a form input element
 *
*/
const VOhModel = {
  mounted(el: HTMLInputElement, binding: Binding) {
    const { value } = binding
    const elValue = el.value
    if (value && elValue !== value) {
      el.value = unref(value)
    }
    el.addEventListener('input', (e: HTMLInputElement) => {
      const curValue = e.target.value;
      if (values.value !== curValue) {
       values.value = curValue
      }
    }, false)
  },
  unmounted(el: HTMLInputElement ) {
    el.removeEventListener('input', (e: HTMLInputElement) => {
      const curValue = e.target.value;
      if (values.value !== curValue) {
       values.value = curValue
      }
    }, false)
  }
}

const values = ref("Hello Vue.js")

</script>

<template>
  <input v-oh-model="values" type="text" />
  <p>{{ values }}</p>
</template>

kalu5 avatar Sep 19 '22 06:09 kalu5