How to use PHP and Vue to implement data filtering function
Introduction:
In modern web applications, data filtering is a very important function. Through data filtering, we can filter and present data according to different conditions and requirements, thereby providing a more personalized and efficient user experience. In this article, we will learn how to use PHP and Vue to implement data filtering functions, and provide specific code examples.
1. Server-side filtering
// Connect to the database and obtain data
function fetchData($filter) {
// 这里假设我们已经连接到数据库,并可以执行查询操作 // 在实际应用中,你需要根据自己的情况进行数据库连接和查询操作 // 这里仅作示例,返回一个假数据 $data = [ ["id" => 1, "name" => "John Doe", "age" => 25], ["id" => 2, "name" => "Jane Smith", "age" => 30], ["id" => 3, "name" => "Mike Johnson", "age" => 35], ["id" => 4, "name" => "Lisa Brown", "age" => 28], ["id" => 5, "name" => "Tom Wilson", "age" => 32], ]; // 进行过滤操作 $filteredData = array_filter($data, function($item) use ($filter) { if ($filter === "") { // 如果没有传入过滤条件,则返回全部数据 return true; } else { // 根据过滤条件返回满足条件的数据 return strpos($item["name"], $filter) !== false; } }); // 返回过滤后的数据 return array_values($filteredData);
}
// Receive the request parameters, call the function to obtain the filtered data, and return the JSON response
$filter = isset($_GET["filter"]) ? $_GET["filter"] : "";
$data = fetchData($filter);
echo json_encode($data);
?>
2. Front-end filtering
vue create filter-demo
Then, create a file named "App.vue" in the src directory and write the following code in the file:
<input v-model="keyword" placeholder="输入关键词进行过滤" />
<ul>
<li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li>
</ul>