vue3中用组合式写法怎么实现搜索功能,格式[{"name":"wjl","age":18},{"name":"fsw","age":28}],存储在缓存中,初始渲染这些数据,搜索之后显示搜索之后的数据
时间: 2024-06-23 10:02:04 浏览: 64
vue实现搜索功能
5星 · 资源好评率100%
在Vue3中使用组合式API(Composition API)实现搜索功能,你可以结合Vuex(状态管理)和自定义事件来完成这个需求。首先,你需要设置一个Vuex store来存储数据和处理搜索逻辑。以下是简单的步骤:
1. 安装依赖:
```bash
npm install vuex vue-router
```
2. 创建Vuex store:
```javascript
// store/index.js
import { createStore } from 'vuex'
import { mapState, mapActions } from 'vuex-composition-api'
export const store = createStore({
state: {
data: [
{ name: "wjl", age: 18 },
{ name: "fsw", age: 28 }
],
searchQuery: "",
},
mutations: {
setSearchQuery(state, query) {
state.searchQuery = query
},
filterData(state, query) {
state.data = state.data.filter(item => item.name.includes(query))
},
},
actions: {
async fetchData() {
// 如果数据是从API或缓存获取,这里做相应的请求
// 在实际项目中,你可能需要模拟数据
// state.data = await ... // 获取的数据
},
async search({ commit }, query) {
commit('setSearchQuery', query)
commit('filterData', query)
},
},
getters: {
filteredData: mapState(['data']),
},
})
```
3. 在组件中使用`setup`函数组合式地处理搜索功能:
```javascript
// App.vue
<script setup>
import { ref, watch, onMounted } from 'vue'
import { store } from '@/store'
const searchQuery = ref("")
const filteredData = computed(() => store.getters.filteredData)
onMounted(async () => {
await store.dispatch('fetchData')
})
function handleSearch(e) {
store.dispatch('search', e.target.value)
}
watch(searchQuery, (query) => {
// 当searchQuery变化时,触发过滤
store.dispatch('search', query)
}, { immediate: true })
</script>
<!-- 在模板中 -->
<input type="text" v-model="searchQuery" @input="handleSearch" placeholder="搜索">
<template>
<div>
<ul>
<li v-for="item in filteredData" :key="item.name">
{{ item.name }} ({{ item.age }})
</li>
</ul>
</div>
</template>
```
4. 相关问题--
阅读全文