Vue.js CRUD functionality
HTML
<div id="app">
<div v-for='(platform, platIndex) in platforms'>
{{ platform.name }} {{ platIndex }}
<button @click="edit(platform)"> Edit Account </button>
<ul v-for='(account, accountIndex) in platform.accounts'>
<li>
{{ account.name }}
<button @click="add(platform)"> Add</button>
<button @click="remove(platform, accountIndex)"> Remove </button>
<button @click="change(platform, accountIndex)"> Change </button>
</li>
</ul>
</div>
</div>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
JavaScript
var app = new Vue({
el: '#app',
data: {
newAccount: { id: 1, name: 'new guy', primary: true },
platforms: [
{
name: 'youtube',
accounts: [
{ id: 1, name: 'youtube.com/123', primary: true },
{ id: 2, name: 'youtube.com/345', primary: false}
]
},
{
name: 'facebook',
accounts: [
{ id: 3, name: 'facebook.com/432', primary: true },
{ id: 1, name: 'facebook.com/321', primary: false}
]
}
]
},
methods: {
add: function(platform) {
var accounts = platform.accounts; // get accounts array
accounts.push(this.newAccount); // push new object into array
},
remove: function(platform, accountIndex) {
var accounts = platform.accounts // get accounts array
accounts.splice(accountIndex, 1); // splice index
},
edit: function(platform) {
var accounts = platform.accounts; // get array
var newObj = this.newAccount; // get updated object
var oldObj = accounts.filter(function(account) {
return account.id == newObj.id; // find old obj
})[0];
for(var key in newObj) {
oldObj[key] = newObj[key]; // replace keys
}
},
change: function(platform, accountIndex) {
var account = platform.accounts[accountIndex]; // get account
var container = (JSON.parse(JSON.stringify(account))); // clone
platform.accounts.splice(accountIndex, 1); // delete original
this.platforms[0].accounts.push(container); // push into new array
}
}
})