Vue 2.0 Hello World

by John Passmore

HTML

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <select v-model="filterCategory">
    <option value="all">All</option>
    <option value="category - a">Category - a</option>
    <option value="category - b">Category - b </option>
    <option value="category - c">Category - c </option>
  </select>
  <input v-model="filterTitle" placeholder="Title"/>
  <ul>
    <li v-for="p in filteredPosts">{{p.title}} - {{p.category_array}}</li>
  </ul>
</div>

JavaScript

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    filterCategory: 'all',
    filterTitle: undefined,
    posts : [
      {
        title: 'post_ab',
        category_array: [
          {
            id: 1,
            slug: 'category - a'
          }, {
            id: 2,
            slug: 'category - b'
          }
        ]
      }, {
        title: 'post_ac',
        category_array: [
          {
            id: 1,
            slug: 'category - a'
          }, {
            id: 3,
            slug: 'category - c'
          }
        ]
      }, {
        title: 'post_bc',
        category_array: [
          {
            id: 2,
            slug: 'category - b'
          }, {
            id: 3,
            slug: 'category - c'
          }
        ]
      }
    ]
  },
  computed: {
  	filteredPosts () {
    	let posts = this.posts
      if (this.filterTitle) {
      	posts = posts.filter((p) => {
        	return p.title.indexOf(this.filterTitle) !== -1
        })
      }
      if(this.filterCategory && this.filterCategory !== 'all') {
      	posts = posts.filter((p) => {
					let foundCategory = p.category_array.findIndex((c) => {
          	return c.slug === this.filterCategory
          })
          return foundCategory !== -1
        })
      }
      return posts
    }
  }
})