自定义v-model

113 阅读1分钟

默认的modelValue与多个自定义v-model

父组件:

<script setup lang="ts">
import {ref} from 'vue'
import VModel from "./components/vModel.vue";

const val = ref('我是默认model的默认值')
const val2 = ref('我是第二个model的默认值')
const val3 = ref('我是不接受参数的model的默认值')
</script>

<template>
  <div class="flex-column">
    <div>val1: {{ val }}</div>
    <div class="my-1">val2: {{ val2 }}</div>
    <div class="mb-2">val3: {{ val3 }}</div>
    <div style="color: white; background-color: blueviolet" class="mb-2">开始改变吧</div>
    <v-model v-model="val" v-model:text-val="val2" v-model:text-val3="val3"/>
  </div>
</template>

自定义v-model组件

<script setup lang="ts">
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  textVal:{
    type: String,
    default: ''
  }
})
const emit = defineEmits(['update:modelValue','update:textVal','update:textVal3'])
const emitValue = (value: string) => {
  emit('update:modelValue', value)
}
const change = (e: any) => {
  emit('update:textVal', e.target.value)
}
const change3 = () => {
  emit('update:textVal3','直接改变3的值')
}
</script>

<template>
  <div @click="emitValue('改变了默认的modelValue')">点击我改变默认的:{{modelValue}}</div>
  <input class="my-1" :value="textVal" @input="change">
  <button @click="change3">点击我改变model3</button>
</template>