Vue.js 中构建国家列表应用

应用场景

该代码片段演示了如何使用 Vue.js 构建一个简单的国家列表应用。该应用允许用户查看所有国家、搜索国家以及添加或删除国家。

基本功能

  • 显示所有国家的列表,包括国家名称和国旗
  • 提供搜索功能,允许用户按国家名称过滤列表
  • 允许用户添加新国家
  • 允许用户编辑现有国家
  • 允许用户删除国家

功能实现步骤及关键代码分析

1. 设置国家数据

首先,我们使用 ref 创建一个响应式 countries 数组来存储国家数据:

const countries = ref([
  {
    name: 'Afghanistan',
    flag: 'https://source.unsplash.com/random/24x24'
  },
  {
    name: 'Albania',
    flag: 'https://source.unsplash.com/random/24x24'
  },
  // ...
])

2. 渲染国家列表

在模板中,我们使用 v-for 循环渲染 countries 数组中的每个国家:

<div class="flex flex-col mt-4">
  <div class="flex items-center justify-between" v-for="country in countries" :key="country.name">
    <div class="flex items-center">
      <img :src="country.flag" alt="" class="w-8 h-8 rounded-full" />
      <div class="ml-4">{{ country.name }}</div>
    </div>
    <div class="country-list-item-actions">
      <button class="px-4 py-2 text-sm font-semibold text-white bg-blue-500 rounded-md">Edit</button>
      <button class="ml-4 px-4 py-2 text-sm font-semibold text-white bg-red-500 rounded-md">Delete</button>
    </div>
  </div>
</div>

3. 搜索国家

我们使用一个 input 元素来实现搜索功能:

<input
  type="text"
  placeholder="Search country..."
  class="px-4 py-2 border border-gray-300 rounded-md"
/>

在 Vue.js 中,我们可以使用 v-model 来双向绑定输入字段的值到一个响应式变量:

const searchQuery = ref('')

然后,我们可以在模板中使用 v-model

<input type="text" placeholder="Search country..." v-model="searchQuery" class="px-4 py-2 border border-gray-300 rounded-md" />

4. 添加国家

我们使用一个按钮来添加新国家:

<button class="ml-4 px-4 py-2 text-sm font-semibold text-white bg-blue-500 rounded-md">Add country</button>

在 Vue.js 中,我们可以使用 @click 事件处理程序来响应按钮点击:

const addCountry = () => {
  // TODO: Implement add country logic
}

然后,我们可以在模板中使用 @click

<button @click="addCountry" class="ml-4 px-4 py-2 text-sm font-semibold text-white bg-blue-500 rounded-md">Add country</button>

5. 编辑国家

我们使用一个按钮来编辑现有国家:

<button class="px-4 py-2 text-sm font-semibold text-white bg-blue-500 rounded-md">Edit</button>

在 Vue.js 中,我们可以使用 @click 事件处理程序来响应按钮点击:

const editCountry = (country) => {
  // TODO: Implement edit country logic
}

然后,我们可以在模板中使用 @click

<button @click="editCountry(country)" class="px-4 py-2 text-sm font-semibold text-white bg-blue-500 rounded-md">Edit</button>

6. 删除国家

我们使用一个按钮来删除国家:

<button class="ml-4 px-4 py-2 text-sm font-semibold text-white bg-red-500 rounded-md">Delete</button>

在 Vue.js 中,我们可以使用 @click 事件处理程序来响应按钮点击:

const deleteCountry = (country) => {
  // TODO: Implement delete country logic
}

然后,我们可以在模板中使用 @click

<button @click="deleteCountry(country)" class="ml-4 px-4 py-2 text-sm font-semibold text-white bg-red-500 rounded-md">Delete</button>

总结与展望

通过这段代码,我们展示了如何使用 Vue.js 构建一个简单的国家列表应用。该应用提供了查看、搜索、添加、编辑和删除国家的功能。

开发经验与收获:

  • 深入理解 Vue.js 的响应式系统和组件化编程
  • 掌握了 Vue.js 中事件处理和数据绑定
  • 了解了如何在 Vue.js 中构建可交互的界面

未来拓展与优化:

  • 实现国家添加、编辑和删除的逻辑
  • 添加分页功能以处理大量国家
  • 允许用户对国家进行排序和过滤
  • 集成地理信息服务以显示国家地图
Login
ECHO recommendation
ScriptEcho.ai
User Annotations

国家/地区选择页面