当前位置: 代码迷 >> 综合 >> 搜索实现(watch)和(computed)
  详细解决方案

搜索实现(watch)和(computed)

热度:82   发布时间:2023-11-24 00:13:12.0

watch监视实现搜索

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><script src="../vue.js"></script><title>Document</title>
</head><body><div id="root"><h1>人员列表</h1><!-- 模糊搜索 --><input type="text" placeholder="请输入名字" v-model="keyword"><ul><li v-for="(item,index) in odel">{
   {item .id}}--{
   {item.name}}--{
   {item.age}}</li></ul></div><script>var vm = new Vue({el: '#root',data: {start: [{id: 001,name: '马冬梅',age: 20}, {id: 002,name: '周冬雨',age: 30}, {id: 003,name: '周杰伦',age: 40}, {id: 004,name: '温兆伦',age: 50}],keyword: '',odel: [],},// watch实现搜索watch: {keyword: {immediate: true,handler(a, b) {// 源数据不能改变this.odel = this.start.filter((item) => {return item.name.indexOf(a) !== -1})}}}})</script>
</body></html>

实现




计算属性实现搜索

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><script src="../vue.js"></script><title>Document</title>
</head><body><div id="root"><h1>人员列表</h1><!-- 模糊搜索 --><input type="text" placeholder="请输入名字" v-model="keyword"><ul><li v-for="(item,index) in odel">{
   {item .id}}--{
   {item.name}}--{
   {item.age}}</li></ul></div><script>var vm = new Vue({el: '#root',data: {start: [{id: 001,name: '马冬梅',age: 20}, {id: 002,name: '周冬雨',age: 30}, {id: 003,name: '周杰伦',age: 40}, {id: 004,name: '温兆伦',age: 50}],keyword: '',},//计算属性刚开始就会调用一次computed: {odel() {// 计算属性的returnreturn this.odel = this.start.filter((item) => {// 这个return 是filter的 return item.name.indexOf(this.keyword) !== -1})}}})</script>
</body></html>

  相关解决方案