1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

贅肉削ぎ落としたInputコンポーネント@Vue3(修正版)

Last updated at Posted at 2023-01-07

強気のタイトルにしてしまったけどVue3触って日が浅いので、(なるべく)贅肉削ぎ落としたInputコンポーネントくらいにしておきます:baby:
Vue3+TypeScriptにおける低レイヤーコンポーネントの基本形。
使いまわせそうだったのでメモメモ:pencil2:

Input.vue
<template>
  <input v-model="value" v-bind="defs.originals" />
</template>

<script setup lang="ts">
import { computed, InputHTMLAttributes } from 'vue'

interface Emits {
  (e: 'update:modelValue', value: string): void
}
const emit = defineEmits<Emits>()

interface Props extends InputHTMLAttributes {
  modelValue: string
}
const props = defineProps<Props>()

const defs = computed(() => {
  const { modelValue, ...originals } = props
  return { modelValue, originals }
})

const value = computed({
  get: () => defs.value.modelValue,
  set: (value: string) => {
    emit('update:modelValue', value)
  }
})
</script>
呼び出し元.vue
<template>
  <div><Input v-model="value" /></div>
  <div><Input v-model="value" type="text" style="background-color: red" /></div>
  <div><Input v-model="value" type="password" style="background-color: green" /></div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import Input from './components/form/Input.vue'

const value = ref('xxxxxxx')
</script>

実行結果
image.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?