作者 Dubem Izuorah
您是否曾經花費數小時跨多個頁面調整相同的網頁佈局,或者努力讓您的 UI 適應不斷變化的數據而不造成破壞?這些常見的挑戰可能會減慢您的開發流程,並導致令人沮喪且容易出錯的程式碼。
透過在運行時基於資料建立佈局,您可以建立靈活、可維護和可擴展的應用程序,輕鬆適應變化。這種方法稱為 動態佈局,消除了重複 HTML 編輯的需要,使您的 UI 與資料無縫保持同步。
在本文中,我們將探討動態佈局如何改變您的開發工作流程並提升您的專案。
當內容頻繁變更或顯示從 API、其他資料來源擷取的響應式 UI 或回應使用者互動時,動態佈局特別有用。
動態版面在各種現實場景中大放異彩,例如:
透過動態產生這些元素,您可以確保一致性、簡化調整並維護乾淨的程式碼庫。
讓我們透過建立動態導覽列來獲得動態佈局的實務經驗。作為參考,這裡是本教學的 Github 儲存庫。
假設您正在開發一個支付平台,需要建立一個乾淨的、可擴展的導覽列元件,如下面的螢幕截圖所示:
使用者登入時的導覽列
沒有使用者登入的導覽列
為了專注於動態佈局,我們不會在這裡深入研究環境設定細節。您可以在我們的 GitHub 儲存庫中找到完整的程式碼範例。
使用的技術:
靜態導覽列元件涉及大量 HTML 標籤和屬性,使得程式碼難以閱讀和維護。
更新此類佈局很容易出錯,尤其是在重複元素共享相同屬性或樣式的情況下。
雖然靜態方法對於起草佈局很有用,但動態佈局對於可維護性和協作來說更可取。
靜態導覽列範例:
? App.vue
<template> <nav class="w-screen border-b py-4"> <div class="container mx-auto flex items-center gap-10"> <!-- Logo --> <NuxtLink href="/" class="flex items-center"> <img src="https://logo.clearbit.com/google.com" class="w-10 h-10 object-contain" /> </NuxtLink> <!-- Dashboard or Home Link --> <NuxtLink v-if="user" href="/dashboard" class="flex items-center"> <PhGauge size="24" /> <span class="ml-2">Dashboard</span> </NuxtLink> <NuxtLink v-else href="/home" class="flex items-center"> <PhHouseSimple size="24" /> <span class="ml-2">Home</span> </NuxtLink> <!-- Spacer --> <div class="ml-auto"></div> <!-- Add Funds Button (Visible only when user is authenticated) --> <button v-if="user" class="flex items-center"> <span class="text-white bg-green-500 px-4 py-2 rounded-lg">Add Funds</span> </button> <!-- User Avatar (Visible only when user is authenticated) --> <div v-if="user" class="flex items-center"> <Avatar src="https://randomuser.me/api/portraits/men/40.jpg" /> <span class="ml-2">Dubem Izuorah</span> </div> <!-- Auth Button --> <button class="flex items-center" @click="user = !user"> <span>{{ user ? 'Logout' : 'Login' }}</span> </button> </div> </nav> <main class="h-64 bg-gray-100 flex justify-center pt-10 text-xl">App Here</main> </template> <script setup lang="jsx"> import { ref } from "vue"; import { NuxtLink, Avatar } from "#components"; import { PhGauge, PhHouseSimple } from "@phosphor-icons/vue"; // Simulate user authentication status const user = ref(true); </script>
雖然靜態佈局可能足以滿足簡單的介面,但動態佈局提供了卓越的可維護性和可擴展性。
To create a dynamic navbar, we’ll want to define our layout data and generate UI components based on this data.
Instead of hard-coding each menu item, we can create a list of menu items in our script with properties like title, image, to, icon, render, and class. This allows us to dynamically generate the navbar based on the data.
? App.vue
<script setup lang="jsx"> // Import necessary components import { ref, computed } from "vue"; import { NuxtLink, Avatar } from "#components"; import { PhGauge, PhHouseSimple } from "@phosphor-icons/vue"; // Simulate user authentication status const user = ref(true); // Define menu items const items = computed(() => [ { key: "logo", image: "https://logo.clearbit.com/google.com", href: "/" }, { icon: user.value ? PhGauge : PhHouseSimple, key: "dashboard", title: user.value ? "Dashboard" : "Home", to: user.value ? "/dashboard" : "/home", }, { key: "spacer", class: "ml-auto", }, { key: "add-funds", render: () => <span class="text-white bg-green-500 px-4 py-2 rounded-lg">Add Funds</span> }, { key: "user", render: () => <Avatar src="https://randomuser.me/api/portraits/men/40.jpg" />, title: "Dubem Izuorah", hide: !user.value }, { key: "auth", title: user.value ? "Logout" : "Login", onClick: () => user.value = !user.value }, ]); // Filter out hidden items const menuItems = computed(() => items.value.filter(item => !item.hide)); </script>
Key Takeaways:
Create an Avatar component used within the dynamic navbar.
? Avatar.vue
<template> <div class="rounded-full w-10 h-10 bg-gray-100 overflow-hidden"> <img class="w-full h-full object-cover" :src="src" /> </div> </template> <script setup> const props = defineProps({ src: { type: String, required: true, }, }) </script>
This component creates a reusable avatar element that can display different images based on the ‘src’ prop passed to it. This makes it flexible and easy to use throughout your application for displaying user avatars or profile pictures.
Use the defined data to render the navbar dynamically.
? App.vue
<template> <nav class="w-screen border-b py-4"> <div class="container mx-auto flex items-center gap-10"> <component v-for="item in menuItems" :key="item.key" :is="item.to ? NuxtLink : 'button'" v-bind="item" @click="item.onClick" class="flex items-center" > <img v-if="item.image" :src="item.image" class="w-10 h-10 object-contain" /> <component v-if="item.render" :is="item.render" /> <component v-if="item.icon" :is="item.icon" :size="24" /> <span v-if="item.title" class="ml-2">{{ item.title }}</span> </component> </div> </nav> <main class="h-64 bg-gray-100 flex justify-center pt-10 text-xl">App Here</main> </template> <script setup lang="jsx"> // The script remains the same as above </script>
Key Takeaways:
By following this approach, you create a dynamic and flexible horizontal navbar that’s easy to extend or modify. This method not only saves time and effort but also ensures your codebase remains clean and maintainable.
Vue JSX allows developers to write Vue components using a syntax similar to React’s JSX, offering greater flexibility and expressiveness. Unlike Vue’s typical template-based approach, JSX allows you to embed HTML-like elements directly inside JavaScript logic. This is particularly useful in dynamic layouts where you need to generate or manipulate UI elements based on dynamic data.
Instead of separating logic and markup across different sections of the component (template and script), JSX enables you to manage both in one cohesive block of code.
In our solution, JSX helps simplify how we dynamically render components like the Avatar or conditional elements such as the “Add Funds” button.
For example, instead of hardcoding these elements into a template, we can dynamically generate them using a render function in JavaScript.
This allows us to update components like the navbar with real-time data, such as user authentication status, without duplicating code or scattering logic across the template and script sections.
By using JSX, we maintain cleaner, more maintainable code, while still leveraging Vue’s reactivity and flexibility.
Now that we understand dynamic layouts, it’s time to put your knowledge into practice. Here are some suggested next steps:
これらの手順を実行すると、動的レイアウトに習熟できるようになるでしょう。動的インターフェイスの作成をさらにスムーズに行うには、Vue.js 開発者に人気のコンポーネント ライブラリである Vuetify を使用した簡単なインターフェイスに関するコースを確認してください。
動的レイアウトを採用することで、開発プロセスを合理化し、アプリケーションの柔軟性を高め、よりクリーンで保守しやすいコードベースを維持できます。今すぐダイナミック レイアウトのプロジェクトへの統合を開始し、ワークフローとアプリケーションの品質に対する変革的な影響を体験してください。
元々は、2024 年 9 月 5 日に https://www.vuemastery.com で公開されました。
以上是使用 Vue jsx 進行動態佈局:靈活且可維護的 UI 指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!