赞
踩
现有如下场景,输入框输入字符,可以过滤如下列表,如下图,当我输入a后,得到另一个结果:
用vue3写法如下:
<template> <div> <input type="text" v-model="obj.mytext" /> <ul> <li v-for="data in filterlist()" :key="data">{{ data }}</li> </ul> </div> </template> <script> import { reactive } from "vue"; export default { setup() { const obj = reactive({ mytext: "", datalist: ["aaa", "bbb", "abc", "bbb", "bcc", "add", "bcd"], }); const filterlist = () => { return obj.datalist.filter((item) => item.includes(obj.mytext)); }; return { obj, filterlist, }; }, }; </script>
现在我们用computed在vue3里也实现这一效果,代码如下:
<template> <div> <input type="text" v-model="obj.mytext" /> <ul> <li v-for="data in computedList" :key="data">{{ data }}</li> </ul> {{ filterlist() }} {{ filterlist() }}{{ computedList }}{{ computedList }} </div> </template> <script> import { reactive, computed } from "vue"; export default { setup() { const obj = reactive({ mytext: "", datalist: ["aaa", "bbb", "abc", "bbb", "bcc", "add", "bcd"], }); const filterlist = () => { console.log("filterlist"); return obj.datalist.filter((item) => item.includes(obj.mytext)); }; const computedList = computed(() => { console.log("computedList"); return obj.datalist.filter((item) => item.includes(obj.mytext)); }); return { obj, filterlist, computedList, }; }, }; </script>
页面效果如下:
我们可以看到控制台打印了两次filterlist,只打印了一次computed,
多次调用computed就能体现出它的优化性能,它会走缓存,它会把第一次执行的结果保存一份,下一次就会直接用第一次保存的结果,不会重复的执行computed里的事情。
刚刚上面那个场景,输入框输入字符,可以过滤如下列表,我们还可以这样写,效果是一样的:
<template> <div> <input type="text" v-model="obj.mytext" @input="handleInput" /> <ul> <li v-for="data in obj.datalist" :key="data">{{ data }}</li> </ul> </div> </template> <script> import { reactive } from "vue"; export default { setup() { const obj = reactive({ mytext: "", datalist: ["aaa", "bbb", "abc", "bbb", "bcc", "add", "bcd"], oldlist: ["aaa", "bbb", "abc", "bbb", "bcc", "add", "bcd"], }); const handleInput = () => { obj.datalist = obj.oldlist.filter((item) => item.includes(obj.mytext)); }; return { obj, handleInput, }; }, }; </script>
现在我们用watch监听输入框双向绑定obj.mytext的改变,然后进行过滤操作,代码如下:
<template> <div> <input type="text" v-model="obj.mytext" /> <ul> <li v-for="data in obj.datalist" :key="data">{{ data }}</li> </ul> </div> </template> <script> import { reactive, watch } from "vue"; export default { setup() { const obj = reactive({ mytext: "", datalist: ["aaa", "bbb", "abc", "bbb", "bcc", "add", "bcd"], oldlist: ["aaa", "bbb", "abc", "bbb", "bcc", "add", "bcd"], }); watch( () => obj.mytext, () => { console.log("watch"); obj.datalist = obj.oldlist.filter((item) => item.includes(obj.mytext)); } ); return { obj, }; }, }; </script>
当我依次输入abc时,页面效果如下:
我们能看到打印了三次watch,说明watch监听事件执行了三次,而watch的写法值得注意的是先import引入watch,然后watch里第一个先写监听的值,第二个写回调方法的调用,即写成:
import { watch } from "vue";
export default {
setup() {
watch(
() => 监听的值,
() => {
//监听的回调方法
}
)
}
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。