Vue: Using Keys for Lifecycle management

by Admiral Potato

HTML

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
	<p>keys: {{ keys }}</p>
	<div>
		<button
			@click="cycle"
		>cycle</button>
	</div>
	<h2>Good way: using a unique value to manage array items</h2>
	<div>
		<goat-component
			v-for="key in keys"
			:key="key"
			:value="key"
		></goat-component>	
	</div>
		<h2>Bad way: using an index to manage array items</h2>
	<div>
		<goat-component
			v-for="(key, index) in keys"
			:key="index"
			:value="key"
		></goat-component>	
	</div>
</div>

CSS

body {
  font-size: 16px;
  line-height: 24px;
  font-family: monospace;
  color: #9f0;
  background-color: #333;
}

JavaScript

Vue.component('goat-component', {
	template: `
<div>value: {{value}} - internal_id: {{internal_id}}</div>
	`,
	props: {
		value: Number
	},
	data: function () {
		return {
			internal_id: Math.random()
		}
	}
})

window.app = new Vue({
	el: '#app',
	data: {
		last_index: 0,
		keys: [
			0
		]
	},
	methods: {
		cycle: function () {
			this.last_index += 1;
			this.keys.push(this.last_index)
			if (this.keys.length > 5) {
				this.keys = this.keys.slice(-5)
			}
		}
	}
});