You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
defineModel with objects currently does not work as many people expect (vuejs/core#11376, vuejs/core#10538). Changing a property on the model's object mutates the object instead of firing 'update:modelValue` with a new updated object.
To use models with object correctly, you must do the following:
<script setup lang="ts">
typeMyObject= { name:string, inner: { innerProp:number }}const props =defineProps<{modelValue:MyObject}>();const emits =defineEmits<{ 'update:modelValue': [value: MyObject] }>()
</script>
<template>
<!-- we cant use v-model here without mutating the prop -->
<MyChildComp@update:modelValue="value => { const clone = structuredClone(modelValue); clone.inner.innerProp = value; $emit('update:modelValue', clone) }":modelValue="modelValue.inner?.innerProp"
/>
</template>
This is both cumbersome and error prone.
Right now, defineModel can not be used with objects while following vue's own best pratice of not mutating props.
Proposal
defineModel should return a proxy that calls 'update:{model-name}'.
Pseudo-code:
functioncreateObjectModelProxy(value: object,upperSetter: (value)=>void){returnnewProxy(value,{get: (target,property,proxy)=>{if(typeoftarget[property]==='object'){// probably want to use caching herereturncreateObjectModelProxy(target[property],(value)=>proxy[property]=value)}elsereturntarget[property];},set: (target,property,value,proxy)=>{upperSetter(Object.assign({},target,{[property]: value}))}})}// defineModel() {// ....if(TSType===TSObject){returncreateObjectModelProxy(model,(value)=>emit('update:modelValue',value))}// ...
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
The problem
defineModel
with objects currently does not work as many people expect (vuejs/core#11376, vuejs/core#10538). Changing a property on the model's object mutates the object instead of firing 'update:modelValue` with a new updated object.To use models with object correctly, you must do the following:
This is both cumbersome and error prone.
Right now,
defineModel
can not be used with objects while following vue's own best pratice of not mutating props.Proposal
defineModel
should return a proxy that calls 'update:{model-name}'.Pseudo-code:
Beta Was this translation helpful? Give feedback.
All reactions