- 官网讲解v-model的原理
<input v-model="searchText" /> //等同于 <input :value="searchText" @input="searchText = $event.target.value" /> //当用在组件上时,v-model 则会这样 <custom-input :model-value="searchText" @update:model-value="searchText = $event" ></custom-input>
- 实现数据双向绑定方式1
子组件声明变量接受父组件传值,并在输入改变的时候触发父组件的更新事件
<template> <input type="text" class="nc_input" v-model="iptval" @input="changeTitle"/> </template> <script setup lang="ts"> import { ref ,watch} from 'vue'; const props=defineProps({ title: { type: String, default: '' } }); let iptval=ref(props.title) interface EMITS { (e: 'update:title', data?: string): void; } const emit = defineEmits<EMITS>(); const changeTitle =(e: any) =>{ let res=(e.target as HTMLInputElement).value emit('update:title', res); } </script>
- 实现数据双向绑定方式2
子组件声明computed接受父组件传值,并在set方法中去触发父组件的更新事件
<template> <input type="text" v-model="iptval" class="nc_input"/> </template> <script setup lang="ts"> import { computed } from 'vue'; const props = defineProps({ modelValue: { type: String, default: '' } }); const emit = defineEmits(['update:modelValue']); const iptval = computed({ get() { return props.modelValue; }, set(e) { emit('update:modelValue', e); } }); </script>
- 在父组件中调用
<template> <div> input1: <nc-input v-model:title="title"></nc-input> input2: <nc-input2 v-model="title2"></nc-input2> <nc-button size="small" @click="print">print</nc-button> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; import NcButton from '@/components/NcButton/Index.vue'; import NcInput from '@/components/NcInput/Index.vue'; import NcInput2 from '@/components/NcInput2/Index.vue'; let title = ref('1'); let title2 = ref(''); const print=()=>{ console.log('title',title.value,'title2',title2.value) } </script>
- 界面展示
- 输入后点击打印按钮
标签:vue,const,自定义,title,ts,vue3,组件,import,ref From: https://www.cnblogs.com/nicoz/p/16731941.html