I have a Vue/Vuetify page that uses a dialog to collect data to submit. It's a big page so I don't want to post the entire file if possible. The problem I am seeing is that the v-model value isn't picked up.
<template>
<div >
<v-dialog v-model="scannedDialog" width="600">
<v-card auto-grow>
<v-card-title primary-title>
Update Scanned Device
</v-card-title>
<v-card-text >
<v-form ref="sendForm" v-model="scannedvalid">
<v-text-field
v-model="selectedScannedDevice.scannedDeviceId"
label="Scanned Internal Id *"
:rules="[rules.required]"
>
</v-text-field>
<v-text-field
v-model="selectedScannedDevice.firstName"
label="First Name *"
:rules="[rules.required]">
</v-text-field>
</v-form>
</v-card-text>
<v-card-actions >
<v-btn
@click="cancelScannedDevice"
outlined
color="primary">
Cancel
</v-btn>
<v-btn
@click="saveScannedDevice"
outlined
:disabled="!scannedvalid"
color="primary">
Save
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
export default {
data() {
return {
selectedScannedDevice: [],
....
};
},
methods: {
async saveScannedDevice() {
console.log( "saveScannedDevice starting with form: " JSON.stringify(this.selectedScannedDevice)
);
...}
</script>
When I run this, the saveScannedDevice always has the result: saveScannedDevice starting with form: []
I cannot find any parsing/formatting errors, but this.selectedScannedDevice never seems to have values in it.
CodePudding user response:
The problem is selectedScannedDevice
is an Array
, and the v-model
s are bound to properties of that Array
:
export default {
data() {
return {
selectedScannedDevice: [], ❌ should not be array
}
}
}
<v-text-field v-model="selectedScannedDevice.scannedDeviceId">
<v-text-field v-model="selectedScannedDevice.firstName">
While it's technically possible for v-model
to attach those properties to the Array
, creating this:
['scannedDeviceId': 'x', 'selectedScannedDevice': 'y']
...that is a misuse of Array
s.
The JSON format only allows numeric indexes, so an Array
with only non-numeric indexes (as in your case) is effectively an empty array, and calling JSON.stringify()
on such an array results in the string representation of that ("[]"
).
Solution
Initialize selectedScannedDevice
to an Object
instead of an Array
.
export default {
data() {
return {
selectedScannedDevice: {}, ✅
}
}
}