v-for: splice()

by edith_tang

HTML

<div id="app">
<button @click="filterBooks">
  找到Gabriel的作品
</button>
<button @click="addBook">
  添加Jane Eyre
</button>
<button @click="filterOut">
  移除《霍乱时期的爱情》和《呼啸山庄》
</button>
  <ul>
    <li v-for="(book, index) in books">
        {{ index + 1 }} - "{{ book.name }}" by {{ book.author }}
    </li>
  </ul>
</div>

CSS

button {
  border: none;
  background-color: pink;
  color: #fff;
  padding: 5px 10px;
}

JavaScript

var app = new Vue({
	el: '#app',
  data: {
  	books: [
    	{
      	name: 'Love in the time of cholera',
        author: 'Gabriel García Márquez'
      },
      {
      	name: 'Wuthering Heights',
        author: 'Emily Bronte'
      },
      {
      	name: 'Becoming',
        author: 'Michelle Obama'
      },
      {
      	name: 'One Hundred Years of Solitude',
        author: 'Gabriel García Márquez'
      }
    ]
  },
  methods: {
  	filterBooks: function() {
    	this.books = this.books.filter(
      	function(item) {
        	return item.author.match(/Gabriel/);
        }
      )
    },
    addBook: function() {
    	Vue.set(this.books, 4, {
      	name: 'Jane Eyre',
        author: 'Charlotte Bronte'
      })
    },
    filterOut: function() {
    	this.books.splice(0, 2);
    }
  }
})