Skip to content

305 - 大写 #2059

@ehxie

Description

@ehxie

Playground: https://stackblitz.com/edit/ynyxxk?file=components%2FInput%2Findex.vue,components%2FInput1%2Findex.vue,App.vue

  • 两种实现方式

参考官方文档:https://vuejs.org/guide/components/v-model.html#handling-v-model-modifiers

<!-- App.vue -->
<script setup>
import { ref } from 'vue';
import Input from './components/Input/index.vue';
import Input1 from './components/Input1/index.vue';
const value = ref('');
const value1 = ref('');
</script>

<template>
  <Input type="text" v-model.capitalize="value" />
  <Input1 type="text" v-model.capitalize="value1" />
</template>

<!-- Input/index.vue-->
<script setup>
import { ref } from 'vue';

const props = defineProps({
  modelValue: String,
  modelModifiers: { default: () => ({}) },
});
const emit = defineEmits(['update:modelValue']);

function emitValue(e) {
  let value = e.target.value;
  if (props.modelModifiers.capitalize) {
    value = value.charAt(0).toUpperCase() + value.slice(1);
  }
  emit('update:modelValue', value);
}
</script>

<template>
  <input :value="modelValue" @input="emitValue" />
</template>


<!-- Input1/index.vue-->
<script setup>
import { ref, computed } from 'vue';

const props = defineProps({
  modelValue: String,
  modelModifiers: { default: () => ({}) },
});
const emit = defineEmits(['update:modelValue']);

const value = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    if (props.modelModifiers.capitalize) {
      value = value.charAt(0).toUpperCase() + value.slice(1);
    }
    emit('update:modelValue', value);
  },
});
</script>

<template>
  <input v-model="value" />
</template>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ehxie

        Issue actions

          305 - 大写 · Issue #2059 · webfansplz/vuejs-challenges