Vue3子組件實現(xiàn)v-model用法的示例代碼
前言
在Vue 3中,實現(xiàn)自定義的input組件并支持v-model綁定,涉及到對modelValue這個默認prop的處理和對應的update:modelValue事件的觸發(fā)。Vue 3使得這個過程比Vue 2更為簡化和靈活,尤其是在可以自定義綁定的屬性和事件名方面。
步驟 1: 創(chuàng)建自定義Input組件
首先,創(chuàng)建一個自定義的Input組件,該組件接收一個modelValue prop,并在用戶輸入時觸發(fā)一個update:modelValue事件。這是v-model的標準實現(xiàn)方式。
<!-- CustomInput.vue -->
<template>
<input
:value="modelValue"
@input="onInput"
>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
// 定義接受的props
const props = defineProps({
modelValue: String
});
// 定義可能觸發(fā)的事件
const emit = defineEmits(['update:modelValue']);
// 輸入事件處理函數(shù)
function onInput(event) {
// 觸發(fā)事件,并傳遞新的值
emit('update:modelValue', event.target.value);
}
</script>
在這個組件中,我們使用defineProps來聲明組件期望接收的prop(modelValue),并用defineEmits聲明組件會觸發(fā)的事件(update:modelValue)。當input元素的值發(fā)生變化時(用戶輸入時),我們觸發(fā)update:modelValue事件,將新的輸入值作為事件的參數(shù)傳遞出去。
步驟 2: 在父組件中使用自定義Input組件
然后,在父組件中使用這個自定義Input組件,并通過v-model進行數(shù)據(jù)綁定。
<!-- ParentComponent.vue -->
<template>
<div>
<CustomInput v-model="textInput" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import CustomInput from './CustomInput.vue';
const textInput = ref('');
</script>
在這個父組件中,textInput是一個響應式引用,存儲用戶在自定義輸入框中輸入的數(shù)據(jù)。通過v-model指令,Vue 自動處理modelValue prop的傳入和update:modelValue事件的監(jiān)聽。
自定義model參數(shù)
如果你需要自定義v-model綁定的屬性名和事件名(例如,如果你希望屬性名不是modelValue,或者你希望事件名不是update:modelValue),你可以在組件上指定v-model的參數(shù)。
自定義屬性和事件名的CustomInput組件:
<!-- CustomInput.vue -->
<template>
<input
:value="customValue"
@input="onInput"
>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
customValue: String
});
const emit = defineEmits(['customUpdate']);
function onInput(event) {
emit('customUpdate', event.target.value);
}
</script>
在父組件中使用:
<!-- ParentComponent.vue -->
<template>
<div>
<CustomInput v-model:customValue="textInput" />
</div>
</template>
在這種情況下,:customValue告訴Vue使用customValue作為prop并監(jiān)聽customUpdate事件來更新textInput。
通過這種方式,你可以在Vue 3中靈活地實現(xiàn)自定義的input組件,允許通過標準或自定義的方式使用v-model進行數(shù)據(jù)雙向綁定。這大大增加了組件的通用性和可重用性。
以上就是Vue3子組件實現(xiàn)v-model用法的示例代碼的詳細內容,更多關于Vue3子組件實現(xiàn)v-model的資料請關注腳本之家其它相關文章!
相關文章
vue3+ts+vite使用el-table表格渲染記錄重復情況
這篇文章主要給大家介紹了關于vue3+ts+vite使用el-table表格渲染記錄重復情況的相關資料,我們可以通過合并渲染、數(shù)據(jù)緩存或虛擬化等技術來減少重復渲染的次數(shù),文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-12-12
Vuex中的getter和mutation的區(qū)別詳解
在現(xiàn)代前端開發(fā)中,狀態(tài)管理是一個不可忽視的話題,而Vuex作為Vue.js的官方狀態(tài)管理庫,在大型應用中扮演著至關重要的角色,當我們使用Vuex進行狀態(tài)管理時,getter和mutation是兩個重要的概念,在本文中,我們將詳細探討getter和mutation的區(qū)別,需要的朋友可以參考下2024-12-12

