I have an array(rows) inside an array(tabs). I want to duplicate the the array. now how do I duplicate the rows array and tabs array separately. Like when I click "Add row" button a row will be added and when I click the "add tab" button the whole tab with row will be added. I am trying this way--
export default {
data() {
return {
tabs: [
{
selectedHouseType: "",
rows: [
{
decorTypes: {},
selectedDecor: "",
selectedDes: "",
selectedQty: "",
selectedRate: "",
line_total: 0,
descriptions: {},
},
],
},
],
};
},
methods: {
addTab() {
this.tabs.push({
selectedHouseType: "",
});
this.tabs[this.tabs.length - 1].rows.push({
selectedDecor: "",
selectedDes: "",
selectedQty: "",
selectedRate: "",
line_total: 0,
decorTypes: {},
});
},
addRow() {
this.tabs[this.tabs.length - 1].rows.push({
selectedDecor: "",
selectedDes: "",
selectedQty: "",
selectedRate: "",
line_total: 0,
decorTypes: {},
});
},
}
CodePudding user response:
Do you mean something like this?
const App = {
name: "App",
template: document.querySelector("#app-template").innerHTML,
data() {
return {
tabs: [
{
selectedHouseType: "",
rows: [
{
decorTypes: {},
selectedDecor: "",
selectedDes: "",
selectedQty: "",
selectedRate: "",
line_total: 0,
descriptions: {},
},
],
},
],
};
},
methods: {
addTab(tab) {
// deep clone is needed here
let newTab = JSON.parse(JSON.stringify(tab));
this.tabs.push(newTab);
},
addRow(tabIndex) {
this.tabs[tabIndex].rows.push({
selectedDecor: "",
selectedDes: "",
selectedQty: "",
selectedRate: "",
line_total: 0,
decorTypes: {},
});
},
},
};
Vue.createApp(App).mount('#app');
<template id="app-template">
<div >
<ul>
<li v-for="(tab, index) in tabs" :key="index">
tab - {{ index }} - {{ tab.rows.length }}
{{ tab.rows }}
<button @click="addTab(tab)">Duplicate this tab</button
><button @click="addRow(index)">Add a new row of this tab</button>
</li>
</ul>
</div>
</template>
<div id="app"></div>
<script src="https://unpkg.com/vue@3"></script>
It was required a Deep Cloning, if not the Javascript reference (of rows array) would be only referenced and not copied. To know more about it see here