<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue学习</title>
<script src="../lib/vue2/vue.js"></script>
</head>
<body>
<div id="app">
查询条件:<input type="text" v-model="query"></input> <button @click="queryPerson">查询</button><br/>
<ul>
<li v-for="person in persons" :key="person.id">
{{person.id}} - {{person.name}} - {{person.age}}
</li>
</ul>
</div>
<script type="text/javascript">
// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false
const vm = new Vue({
data() {
return {
query: '',
persons: [{
id:1,
name: '张三',
age: 18
}, {
id:2,
name: '李四',
age: 20
}, {
id:3,
name: '王五',
age: 22
}]
}
},
methods: {
queryPerson() {
this.persons = this.persons.filter(person => person.name.indexOf(this.query) !== -1)
}
}
})
vm.$mount('#app')
</script>
</body>
</html>
在上面的案例中,通过修改persons的数据,达到了页面上筛选的效果。
但实际中,我们可能就只是想改变一下页面的展示,对于数据本身是不希望修改的。那我们就可以使用计算属性来做
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue学习</title>
<script src="../lib/vue2/vue.js"></script>
</head>
<body>
<div id="app">
查询条件:<input type="text" v-model="query"></input>
<ul>
<li v-for="person in filterPersons" :key="person.id">
{{person.id}} - {{person.name}} - {{person.age}}
</li>
</ul>
</div>
<script type="text/javascript">
// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false
const vm = new Vue({
data() {
return {
query: '',
persons: [{
id:1,
name: '张三',
age: 18
}, {
id:2,
name: '李四',
age: 20
}, {
id:3,
name: '王五',
age: 22
}]
}
},
methods: {
queryPerson() {
this.persons = this.persons.filter(person => person.name.indexOf(this.query) !== -1)
}
},
computed: {
// 监听 query 属性的变化,返回一个过滤后的 persons 数组
filterPersons(){
return this.persons.filter(person => person.name.indexOf(this.query) !== -1)
}
}
})
vm.$mount('#app')
</script>
</body>
</html>