I’m passing data to Modal for editing. The problem is whenever my products data is updated (Every 5s via fetchData), input field in modal also changed. How to prevent it?
Below is a simplified version of my code.
<div id="app">
<div class="modal" id="modal1">
<form method="post">
<input type="text" :value="passedData.category" />
<input type="text" :value="passedData.rating" />
<input type="text" :value="passedData.price" />
<input type="text" :value="passedData.stock" />
<button>Submit</button>
</form>
</div>
<table>
<tr v-for="item in items">
<td>{{ item.sku }}</td>
<td>{{ item.stock }}</td>
<td><button @click="openModal('modal1', item)">Edit</button></td>
</tr>
</table>
</div>
<script>
const app = Vue.createApp({
data() {
return {
items: [],
passedData: [],
};
},
mounted() {
this.fetchData();
setInterval(this.fetchData, 5000);
},
methods: {
async fetchData() {
const response = await fetch("https://dummyjson.com/products");
const data = await response.json();
this.items = data.products;
},
openModal(idModal, item) {
this.passedData = Object.assign({}, item);
},
},
});
app.mount("#app");
</script>
2
Answers
As per this documentation – in your
<input>
‘s, usev-model
instead of:value
– i.e.In the "openModal" method, when you open the modal window, you have to make an independent clone of the passedData variable.
Which is also poorly defined – you claim it’s an Array, but in the form you access it as an object.
And be careful: creating an independent clone can be a challenge. Better get "npm i lodash" and import cloneDeep in this component via import cloneDeep from "lodash/cloneDeep".