Skip to content

305 - 大写 #2139

@jay6697117

Description

@jay6697117
// 你的答案
// 第一种方案 vModelText
<script setup>
import { ref, vModelText } from 'vue';
const value = ref('');
vModelText.beforeUpdate = (el, binding) => {
  if (el.value && binding.modifiers.capitalize) {
    el.value = el.value.charAt(0).toUpperCase() + el.value.slice(1);
  }
};
</script>

<template>
  <h1>{{ value }}</h1>
  <input type="text" v-model.capitalize="value" />
</template>

// 第二种方案自定义组件
// App.vue
<script lang="ts" setup>
import { ref } from 'vue';
import Son from './Son.vue'
const value = ref('');
</script>

<template>
  <h1>{{ value }}</h1>
  <Son  v-model.capitalize="value" />
</template>
// Son.vue
<script lang="ts" setup>
const props = defineProps({
  modelValue: String,
  modelModifiers: { default: () => ({}) }
})

const emit = defineEmits(['update:modelValue'])

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

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions