'vue 3 radio button revert back if user canceled
I am having some issues with some radio buttons in vue 3
From the parent component I am passing an object to the child where is the data displayed and where I want to make one version default:
<template>
<table>
...
<tr v-for="(vf, index) in version.files" :key="vf.id">
...
<td>
<input type="radio" name="defaultVersion" v-model="vf.default" :checked="vf.default" @change="onChangeDefault(index)" @click="onClickDefault">
</td>
</tr>
</table>
</template>
props: {
version: Object // the prop object received
},
setup(props) {
const {version} = toRefs(props) // version should be now reactive
// use this variable to know where is the index that contains the default value
let defaultVersionIndex = 0
const onClickDefault = () => {
// check on click what is the current version default and store the index
for(let i = 0; i < version.value.files.length; i++) {
if(version.value.files[i].default) {
defaultVersionIndex = i
}
}
}
const onChangeDefault = (index) => {
let text = "Change default?\nEither OK or Cancel.";
if (confirm(text) == true) {
// user press ok => make API call
} else {
// if the user canceled => set the default radio checked (previously)
version.value.files[index].default = false // change back from what user has selected
version.value.files[defaultVersionIndex].default = true // set back the original radio checked (previously)
}
}
return {
version,
onClickDefault,
onChangeDefault
}
}
When click on a radio (unchecked) it changes visually - but in the version.files no changes ... what I am missing ???
You get the idea .... when the user cancel the action to revert back the radio button. I choose radio because only one can be default.
UPDATE 1
make some changes on input by binding the value (to make sure the value is boolean not on, off)
<input type="radio" :value="vf.default" name="defaultVersion" v-model="vf.default" :checked="vf.default" @change="onChangeDefault(index)" @click="onClickDefault">
and on canceled action :
version.value.files[index].default = !version.value.files[index].default
version.value.files[defaultVersionIndex].default = !version.value.files[defaultVersionIndex].default
the values in the object version.files now changes but visually not working like it should...
Solution 1:[1]
Solved.
On input:
<input type="radio" :value="vf.id" name="defaultVersion" v-model="defaultValue" :checked="vf.id === defaultValue" @change="onChangeDefault(vf.id)" @click="onClickDefault">
Created a vmodel that hold the id for the default value
const defaultValue = ref(0)
// store the previous default value (id)
let previousDefault = 0
const onClickDefault = () => {
previousDefault = defaultValue.value // this is the magic :)
}
the when the user canceled:
defaultValue.value = previousDefault
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | calin24 |
