接上文,需求:从后端获取数据+在输入框中输入作者名字筛选出作者的书
展示上文:
// 子组件:
<template>
<div>{{list}}</div>
</template>
<script>
import { ref, onMounted } from 'vue'
// 发起接口请求
function fetchList() {
let res = [
{id:'1',name:'JAVA',author:'s0nei',price:6},
{id:'2',name:'HTML',author:'d1iber',price:7},
{id:'3',name:'JS',author:'j1lion',price:8},
{id:'4',name:'C',author:'s0nei',price:9}
]
return res
}
export default{
setup(props) {
let list = ref([]) // 创建了一个响应式变量,用.value获取响应式值,也可以不用响应式,看上文最后的3个辨析
const getList = async () => {
list.value = await fetchList()
}
onMounted(getList ) // 在 `mounted` 时调用 `getList`完整写法是:onMounted( () => { getList() } )
return {
list
}
},
}
</script>
如果继续按上文写就是这样(只展示子组件,父组件和上文一样不变的):
// 子组件:
<template>
<input type="text" v-model="keyword" />
<div>{{list}}</div>
<div>{{listNew}}</div>
</template>
<script>
import { ref, onMounted, watch } from 'vue'
function fetchList() {
let res = [
{id:'1',name:'JAVA',author:'s0nei',price:6},
{id:'2',name:'HTML',author:'d1iber',price:7},
{id:'3',name:'JS',author:'j1lion',price:8},
{id:'4',name:'C',author:'s0nei',price:9}
]
return res
}
export default{
setup(props) {
let list = ref([])
let keyword = ref('') // new
let listNew = ref([]) // new
const getList = async () => {
list.value = await fetchList()
}
const searchList = (keyword) => { // new
listNew .value = keyword==='' ? list : list.reduce((t,v)=>{
if(v.author===keyword) t = [...t,v]
return t
},[])
}
onMounted(getList)
watch(keyword, searchList) // new
return {
list,
keyword,
listNew
}
},
}
</script>
可以看到,新增的功能和原先的功能穿插在了一起,如果业务多了,将会更复杂,所以要将其拆分
<template>
<div>
<input type="text" v-model="keyword" />
<div>{{list}}</div>
<div>{{listNew}}</div>
</div>
</template>
<script>
import { ref, onMounted, watch } from 'vue'
import useList from './useList'
import useFilter from './useFilter'
export default{
setup(props) {
const { res:list } = useList()
let keyword = ref('')
const { res:listNew } = useFilter(list, keyword)
return {
list,
keyword,
listNew
}
},
}
</script>
// useList.js中的内容
import { ref, onMounted } from 'vue';
function fetchList() {
let res = [
{id:'1',name:'JAVA',author:'s0nei',price:6},
{id:'2',name:'HTML',author:'d1iber',price:7},
{id:'3',name:'JS',author:'j1lion',price:8},
{id:'4',name:'C',author:'s0nei',price:9}
]
return res
}
export default function useList(){
let res = ref([])
const getList = () => {
res.value = fetchList()
}
onMounted(()=>{
getList()
})
return {
res
}
}
// useFilter中的内容
import { ref, watch } from 'vue'
export default function useFilter(list, keyword) {
let res = ref([])
const getList = (keyword) => {
res.value = keyword==='' ? list : list.reduce((t,v)=>{
if(v.author===keyword) t = [...t,v]
return t
},[])
}
watch(keyword, getList)
return {
res
}
}