搜尋
首頁web前端js教程使用 Vue jsx 進行動態佈局:靈活且可維護的 UI 指南

Dynamic Layouts with Vue jsx: A Guide to Flexible and Maintainable UIs

作者 Dubem Izuorah

您是否曾經花費數小時跨多個頁面調整相同的網頁佈局,或者努力讓您的 UI 適應不斷變化的數據而不造成破壞?這些常見的挑戰可能會減慢您的開發流程,並導致令人沮喪且容易出錯的程式碼。

動態佈局簡介

透過在運行時基於資料建立佈局,您可以建立靈活、可維護和可擴展的應用程序,輕鬆適應變化。這種方法稱為 動態佈局,消除了重複 HTML 編輯的需要,使您的 UI 與資料無縫保持同步。

在本文中,我們將探討動態佈局如何改變您的開發工作流程並提升您的專案。

為什麼要使用動態佈局?

當內容頻繁變更或顯示從 API、其他資料來源擷取的響應式 UI 或回應使用者互動時,動態佈局特別有用。

動態佈局的好處

  • 靈活性:基於底層資料輕鬆調整UI元件,無需修改HTML或範本程式碼。
  • 可維護性:堅持DRY(Don’t Repeat Yourself)原則,減少重複程式碼,簡化維護。
  • 可擴充性:以程式設計方式管理您的 UI,允許輕鬆更新、新增或刪除項目。
  • 減少錯誤:盡量減少手動 HTML 編輯,降低錯誤的可能性。
  • 增強回應能力:根據條件動態顯示或隱藏 UI 元素,使介面對使用者互動或資料變化的回應更加靈敏。

動態佈局的實際場景

動態版面在各種現實場景中大放異彩,例如:

  • 表單:對於表單較多的應用程序,最好將表單欄位抽象化為與某些驗證庫配對的計算屬性。在佈局中,您可以循環遍歷屬性以有條件地顯示表單欄位和屬性,例如標籤、類別名稱、驗證訊息等。
  • 部落格文章清單:根據資料動態管理和更新每張明信片的內容。
  • 內容區塊:有效組織和顯示不同的內容元素。
  • 使用者清單、導覽項目、儀表板:確保一致的樣式和輕鬆調整,無需手動 HTML 更新。
  • 網站部分:動態生成部分以保持有凝聚力且易於調整的佈局。

透過動態產生這些元素,您可以確保一致性、簡化調整並維護乾淨的程式碼庫。

建立動態導覽列

讓我們透過建立動態導覽列來獲得動態佈局的實務經驗。作為參考,這裡是本教學的 Github 儲存庫。

要求

假設您正在開發一個支付平台,需要建立一個乾淨的、可擴展的導覽列元件,如下面的螢幕截圖所示:

Dynamic Layouts with Vue jsx: A Guide to Flexible and Maintainable UIs

使用者登入時的導覽列

Dynamic Layouts with Vue jsx: A Guide to Flexible and Maintainable UIs

沒有使用者登入的導覽列

設定環境

為了專注於動態佈局,我們不會在這裡深入研究環境設定細節。您可以在我們的 GitHub 儲存庫中找到完整的程式碼範例。

使用的技術:

  1. Nuxt — Vue框架
  2. Nuxt TailwindCSS — 樣式
  3. Phosphor-icons Vue — 圖示元件

靜態方法

靜態導覽列元件涉及大量 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  class="w-10 h-10 object-contain lazy" src="/static/imghwm/default1.png" data-src="https://logo.clearbit.com/google.com" alt="使用 Vue jsx 進行動態佈局:靈活且可維護的 UI 指南" >
      </nuxtlink>

<!-- Dashboard or Home Link -->
      <nuxtlink v-if="user" href="/dashboard" class="flex items-center">
        <phgauge size="24"></phgauge>
        <span class="ml-2">Dashboard</span>
      </nuxtlink>
      <nuxtlink v-else href="/home" class="flex items-center">
        <phhousesimple size="24"></phhousesimple>
        <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"></avatar>
        <span class="ml-2">Dubem Izuorah</span>
      </div>
      <!-- Auth Button -->
      <button class="flex items-center">
        <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>

雖然靜態佈局可能足以滿足簡單的介面,但動態佈局提供了卓越的可維護性和可擴展性。

Dynamic Approach

To create a dynamic navbar, we’ll want to define our layout data and generate UI components based on this data.

Defining the 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
  },
  {
    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:

  1. Reactive Layout : Use computed properties to update the layout based on reactive data like user.
  2. Conditional Rendering : Apply different values using ternary operators based on state.
  3. JSX Integration : Utilize JSX to include HTML elements and Vue components directly within property values.
  4. Dynamic Properties : Use properties like hide to conditionally display items.
  5. Event Handling : Store functions or event handlers (e.g., onClick) within data objects.
  6. Modular Data Management : Move layout data to Vue composables or external JSON files for better organization.

Defining the Avatar Component

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 lazy" src="/static/imghwm/default1.png" data-src="src" : alt="使用 Vue jsx 進行動態佈局:靈活且可維護的 UI 指南" >
  </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.

Building the Layout

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" class="flex items-center">
        <img  class="w-10 h-10 object-contain lazy" src="/static/imghwm/default1.png" data-src="item.image" v-if="item.image" : alt="使用 Vue jsx 進行動態佈局:靈活且可維護的 UI 指南" >
        <component v-if="item.render" :is="item.render"></component>
        <component v-if="item.icon" :is="item.icon" :size="24"></component>
        <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:

  1. v-bind Usage : Attach multiple properties to elements simultaneously, keeping the template clean.
  2. Unique Keys : Use the key attribute to prevent rendering issues during dynamic updates.
  3. Dynamic Components : Utilize Vue’s dynamic components to render different elements based on data.
  4. Event Binding : Attach events like @click dynamically based on data properties.
  5. Component Modularity : Break down components further and import them as needed for better scalability.

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.

Enhancing Flexibility with Vue JSX

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.

Next Steps

Now that we understand dynamic layouts, it’s time to put your knowledge into practice. Here are some suggested next steps:

  1. 既存のプロジェクトのリファクタリング : 現在のプロジェクトのうち、特に HTML やコンポーネント ロジックが繰り返される領域で、動的レイアウトによって効率と可読性が向上する部分を特定し、リファクタリングします。
  2. CMS との統合 : CMS または他のシステムを動的レイアウトと統合して、さらに動的で応答性の高いユーザー インターフェイスを作成してみてください。
  3. チームとのコラボレーション : 動的レイアウトに関する洞察をチームと共有します。プロジェクトで動的レイアウトを共同利用して生産性を向上させ、継続的な改善の文化を促進する方法について話し合います。
  4. 高度なユースケースの探索 : 動的レイアウトのより高度なアプリケーションの探索を続けます。熟練は一貫した練習と探究から生まれます。

これらの手順を実行すると、動的レイアウトに習熟できるようになるでしょう。動的インターフェイスの作成をさらにスムーズに行うには、Vue.js 開発者に人気のコンポーネント ライブラリである Vuetify を使用した簡単なインターフェイスに関するコースを確認してください。

動的レイアウトを採用することで、開発プロセスを合理化し、アプリケーションの柔軟性を高め、よりクリーンで保守しやすいコードベースを維持できます。今すぐダイナミック レイアウトのプロジェクトへの統合を開始し、ワークフローとアプリケーションの品質に対する変革的な影響を体験してください。

元々は、2024 年 9 月 5 日に https://www.vuemastery.com で公開されました。


以上是使用 Vue jsx 進行動態佈局:靈活且可維護的 UI 指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

如何安裝JavaScript?如何安裝JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能