VueJS Array Mutate
by David Rodenas
HTML
<script src="https://unpkg.com/vue@1.0.28/dist/vue.js"></script>
<div id="vue-instance">
<ul>
<li v-for="item in inventory">
{{ item.name }} - ${{ item.price }}
</li>
</ul>
First item: {{ inventory[0].name }} - ${{ inventory[0].price }}<br>
Second item: {{ inventory[1].name }} - ${{ inventory[1].price }}<br>
<button @click="swap">Swap</button>
<button @click="swapAndIncrease">Swap and Increase</button>
</div>
JavaScript
var vm = new Vue({
el: '#vue-instance',
data: {
inventory: [
{name: 'MacBook Air', price: 1000},
{name: 'MacBook Pro', price: 1800},
{name: 'Lenovo W530', price: 1400},
{name: 'Acer Aspire One', price: 300}
]
},
methods: {
swap: function() {
var t = this.inventory[0];
this.inventory[0] = this.inventory[1];
this.inventory[1] = t;
},
swapAndIncrease: function() {
this.swap();
this.inventory[0].price += 100;
},
}
});