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

使用 Vue jsx 進行動態佈局:靈活且可維護的 UI 指南

Sep 07, 2024 am 06:40 AM

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 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>
登入後複製

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

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</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:

  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" :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.

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"
        @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:

  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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1655
14
CakePHP 教程
1414
52
Laravel 教程
1307
25
PHP教程
1255
29
C# 教程
1228
24
神秘的JavaScript:它的作用以及為什麼重要 神秘的JavaScript:它的作用以及為什麼重要 Apr 09, 2025 am 12:07 AM

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

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

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

JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

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實現跨平台開發,提高開發效率。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

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

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

從C/C到JavaScript:所有工作方式 從C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

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

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

See all articles