1. Classification of data methods:
(1) Changes in the original array
push
pop
unshift
shift
reverse
sort
splice
(2) The original array remains unchanged, resulting in a new array
slice
concat
filter
For methods that change the original array, you can update the view directly.
For methods where the original array remains unchanged, you can use a new array to replace the original one so that the view changes.
Sample code:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>vue Example</title>
</head>
<body>
<div id="app">
<ul>
<template v-for="book in books">
<li>Title:{{book.name}}</li>
<li>Author:{{book.author}}</li>
</template>
</ul>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
books: [{
name: 'vuejs',
author: 'a'
},
{
name: 'js senior',
author: 'b'
},
{
name: 'java',
author: 'c'
}
]
}
});
//You can change the view directly
//app.books.push({name: 'c++',author: 'd'});
//The original array needs to be updated
app.books = app.books.concat([{name: 'c++',author: 'd'}]);
</script>
</body>
</html>
Note: The following will not trigger an update of the view.
(1) Set items directly by index.
(2) modifying the length of the array,app.books.length=1.
If you do not want to change the original array, you can filter the array by using a computed property, such as:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>vue Example</title> </head> <body> <div id="app"> <ul> <template v-for="book in filterBooks"> <li>Title:{{book.name}}</li> <li>Author:{{book.author}}</li> </template> </ul> </div> <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { books: [{ name: 'vuejs', author: 'a' }, { name: 'js Advanced 111', author: 'b' }, { name: 'java33333', author: 'c' } ] }, computed:{ filterBooks:function(){ return this.books.sort(function(a,b){ return a.name.length>b.name.length?1:-1 }) } } }); </script> </body> </html>
The above codes are sorted by book name from short to long.This does not modify the original array.