在开发复杂的单页面应用程序时,组件化开发是一种有效组织代码和提高代码可维护性的方法。本篇博客将演示如何使用 Vue.js 创建一个组件化菜品展示界面,展示菜品图片和名称。
该组件主要由以下部分组成:
1. 创建 Vue.js 组件
首先,创建一个名为 Dishes.vue
的 Vue.js 组件文件:
<template>
<div class="bg-gray-100">
<van-nav-bar
title="Dishes"
left-arrow
fixed
:border="false"
class="bg-yellow-500 text-white"
/>
<div class="flex flex-col items-center justify-center">
<div class="w-full">
<van-grid :column-num="3" :border="false" class="mt-4">
<van-grid-item
v-for="item in dishes"
:key="item.id"
class="text-center"
>
<img :src="item.image" alt="" class="w-full h-full object-cover" />
<div class="text-gray-500 text-sm mt-2">
{{ item.name }}
</div>
</van-grid-item>
</van-grid>
</div>
</div>
</div>
</template>
<script lang="tsx" setup>
import { ref } from "vue";
const dishes = ref([
{
id: 1,
name: "Dish 1",
image: "https://source.unsplash.com/random/300x300",
},
{
id: 2,
name: "Dish 2",
image: "https://source.unsplash.com/random/300x300",
},
{
id: 3,
name: "Dish 3",
image: "https://source.unsplash.com/random/300x300",
},
{
id: 4,
name: "Dish 4",
image: "https://source.unsplash.com/random/300x300",
},
{
id: 5,
name: "Dish 5",
image: "https://source.unsplash.com/random/300x300",
},
{
id: 6,
name: "Dish 6",
image: "https://source.unsplash.com/random/300x300",
},
]);
</script>
<style>
.bg-yellow-500 {
background-color: #f59e0b;
}
</style>
2. 创建菜品数据状态
在 main.js
文件中,创建一个 Vuex 状态模块来存储菜品数据:
const store = new Vuex.Store({
state: {
dishes: [],
},
getters: {
getDishes: (state) => state.dishes,
},
mutations: {
setDishes(state, dishes) {
state.dishes = dishes;
},
},
actions: {
fetchDishes({ commit }) {
// Fetch dishes from API or database
const dishes = [
{
id: 1,
name: "Dish 1",
image: "https://source.unsplash.com/random/300x300",
},
// ...
];
commit("setDishes", dishes);
},
},
});
3. 使用组件
在需要展示菜品的页面中,使用 Dishes
组件:
<template>
<div>
<Dishes />
</div>
</template>
<script>
import Dishes from "./components/Dishes.vue";
export default {
components: { Dishes },
};
</script>
通过组件化开发,我们可以将复杂的用户界面分解成可重用的组件,从而提高代码的可维护性和可扩展性。本示例展示了如何使用 Vue.js 创建一个菜品展示组件,并通过 Vuex 管理数据。
未来,该组件可以进一步扩展,例如: