该代码片段演示了如何使用 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 构建一个简单的国家列表应用。该应用提供了查看、搜索、添加、编辑和删除国家的功能。
开发经验与收获:
未来拓展与优化: