功能描述:
- 主页面 (Index.vue) 显示一个不可编辑的搜索框、项目总数和项目列表。
- 点击主页面的搜索框会导航到搜索页面 (Search.vue)。
- 搜索页面包含一个可编辑的搜索框和项目列表。
- 在搜索页面输入内容时,会调用后端 API 获取匹配的项目数据。
- 项目列表使用单独的组件 (ProjectList.vue) 来展示,可以在两个页面中复用。
使用Vue 3 + UniApp 实现的列表展示页面和搜索页面的示例:
- 创建列表组件 ProjectList.vue:
<template>
<view class="project-list">
<view v-for="(item, index) in projects" :key="index" class="project-item">
<text>{{ item.name }}</text>
</view>
</view>
</template>
<script>
export default {
name: 'ProjectList',
props: {
projects: {
type: Array,
default: () => []
}
}
}
</script>
<style scoped>
.project-list {
padding: 10px;
}
.project-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
</style>
- 创建主页面 index.vue:
<template>
<view class="container">
<view class="search-bar" @tap="goToSearch">
<input type="text" placeholder="请输入项目名" disabled />
</view>
<view class="total-count">
总项目数: {{ totalCount }}
</view>
<project-list :projects="projects"></project-list>
</view>
</template>
<script>
import ProjectList from '@/components/ProjectList.vue'
import { getProjects } from '@/api/projects'
export default {
components: {
ProjectList
},
data() {
return {
projects: [],
totalCount: 0
}
},
onLoad() {
this.fetchProjects()
},
methods: {
async fetchProjects() {
try {
const response = await getProjects()
this.projects = response.data.projects
this.totalCount = response.data.total
} catch (error) {
console.error('Failed to fetch projects:', error)
}
},
goToSearch() {
uni.navigateTo({
url: '/pages/search/search'
})
}
}
}
</script>
<style scoped>
.container {
padding: 20px;
}
.search-bar {
background-color: #f5f5f5;
padding: 10px;
border-radius: 5px;
}
.total-count {
margin: 10px 0;
font-weight: bold;
}
</style>
- 创建搜索页面 search.vue:
<template>
<view class="container">
<view class="search-bar">
<input
type="text"
v-model="searchQuery"
placeholder="请输入项目名"
@input="onSearch"
/>
</view>
<project-list :projects="searchResults"></project-list>
</view>
</template>
<script>
import ProjectList from '@/components/ProjectList.vue'
import { searchProjects } from '@/api/projects'
export default {
components: {
ProjectList
},
data() {
return {
searchQuery: '',
searchResults: []
}
},
methods: {
async onSearch() {
if (this.searchQuery.length > 0) {
try {
const response = await searchProjects(this.searchQuery)
this.searchResults = response.data.projects
} catch (error) {
console.error('Failed to search projects:', error)
}
} else {
this.searchResults = []
}
}
}
}
</script>
<style scoped>
.container {
padding: 20px;
}
.search-bar {
background-color: #f5f5f5;
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
}
</style>
- 创建 API 文件 projects.js:
import axios from 'axios'
const API_URL = 'your_api_base_url'
export function getProjects() {
return axios.get(`${API_URL}/projects`)
}
export function searchProjects(query) {
return axios.get(`${API_URL}/projects/search`, {
params: { q: query }
})
}
- 在 main.js 中配置 axios:
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
关注微信公众号温暖前端,不定期分享前端知识点和前端资料↓↓↓