一、默认computed筛选方式
<template>
<div>
<input type="text" v-model="mytext">
<ul>
<li v-for="data in computedList" :key="data">
{{data}}
</li>
</ul>
</div>
</template>
<script>
import { reactive,toRefs, computed } from 'vue';
export default {
setup(){
const state = reactive({
mytext:"",
datalist:["aaa","aab","abc","bbc","bcd","aef","bdf","cde"]
})
const computedList = computed(()=>
state.datalist.filter(item=>item.includes(state.mytext))
)
return {
computedList,
...toRefs(state) //转化陈ref 响应式
}
}
}
</script>
二、改造代码 自定义筛选过滤 hooks
vue文件:
<template>
<div>
<input type="text" v-model="mytext">
<ul>
<li v-for="data in computedList" :key="data">
{{ data }}
</li>
</ul>
</div>
</template>
<script>
import { ref } from 'vue';
//自定义的hooks
import useSearch from './search' //过滤
export default {
setup() {
const datalist = ref([])
setTimeout(() => {
datalist.value = ["aaa", "aab", "abc", "sdew", "rtea", "aef", "bdf", "cde"]
}, 2000)
return {
...useSearch(datalist)
}
}
}
</script>
search.js
import { ref,computed } from 'vue';
function UseSearch(datalist) {
const mytext = ref("")
const computedList = computed(() =>
datalist.value.filter(item => item.includes(mytext.value))
)
return {
mytext,
computedList
}
}
export default UseSearch