Watching form object and Searching

by bc_rikko

HTML

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<main id="app">
  <form>
    <div>
      <label>Title</label>
      <input type="text" v-model="form.title">
    </div>
    <div>
      <label>Status</label>
      <label>
        <input type="checkbox" value="done" v-model="form.status">
        DONE
      </label>
      <label>
        <input type="checkbox" value="progress" v-model="form.status">
        PROGRESS
      </label>
      <label>
        <input type="checkbox" value="todo" v-model="form.status">
        TODO
      </label>
    </div>
  </form>
  <table>
    <thead>
      <tr>
        <th>Title</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody>
      <tr
        v-for="(todo, i) in filteredTodos"
        :key="i"
      >
        <td>{{ todo.title }}</td>
        <td>{{ todo.status }}</td>
      </tr>
    </tbody>
  </table>
</main>

JavaScript

// import vue@2.5
const todos = [
  { title: 'test1', status: 'done' },
  { title: 'test2', status: 'progress' },
  { title: 'test3', status: 'todo' },
  { title: 'test4', status: 'done' },
  { title: 'test5', status: 'progress' },
  { title: 'test6', status: 'todo' }
]

new Vue({
  el: '#app',
  data () {
    return {
      todos: todos,
      filteredTodos: [],
      form: {
        title: '',
        status: ['done', 'progress', 'todo']
      }
    }
  },
  watch: {
    // formオブジェクト内のすべての変更を監視する
    form: {
      handler () {
      	this.search()
      },
      deep: true
    }
  },
  created () {
  	this.filteredTodos = this.todos.slice()
  },
  methods: {
		search () {
      // APIコール(GET /todos)
      setTimeout(() => {
        // 検索
        this.filteredTodos = this.todos.slice().filter(a => {
        	const isMatchedTitle = this.form.title ? a.title.includes(this.form.title) : true
          const isMatchedStatus = this.form.status.includes(a.status)
        
          return isMatchedTitle && isMatchedStatus
        })
      }, 500)
    }
  }
})