Vue sorted list

by Guillaume Chau

HTML

<!-- Include the library in the page -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.rawgit.com/Marak/faker.js/master/examples/browser/js/faker.js"></script>

<!-- App -->
<div id="app">
  <provider :items="items"></provider>
</div>

JavaScript

const items = []

for (var i = 0; i < 10000; i++) {
	items.push({
  	name: faker.name.findName(),
  })
}

Vue.component('scroller', {
	props: ['items'],
  watch: {
  	items () {
    	console.log('[scroller] items changed')
    },
  },
  template: `<div class="scroller">
  	<div class="item" v-for="item of items">{{ item.name }}</div>
  </div>`,
})


Vue.component('provider', {
	props: ['items'],
  data: () => ({
  	enableSort: false,
  	sorting: -1,
  }),
  computed: {
  	sortedItems () {
    	if (this.enableSort) {
    		return this.items.slice(0).sort((a, b) => a.name < b.name ? this.sorting : -this.sorting )
     	} else {
    		return this.items
      }
    },
  },
  watch: {
  	sortedItems () {
    	console.log('[provider] sortedItems changed')
    },
  },
  template: `<div class="provider">
  	<button @click="enableSort = !enableSort">Toggle sort</button>
  	<button @click="sorting *= -1">Toggle order</button>
  	<scroller :items="sortedItems"></scroller>
  </div>`,
})


// New VueJS instance
var app = new Vue({
	// CSS selector of the root DOM element
  el: '#app',
  // Some data
  data: () => ({
    items,
  }),
})