検索
ホームページウェブフロントエンドjsチュートリアルVue jsx を使用した動的レイアウト: 柔軟で保守可能な UI のガイド

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

作者 デュベム・イズオラ

複数のページにわたって同じ Web レイアウトを調整するのに何時間も費やしたことや、UI を中断することなく変化するデータに適応させるのに苦労したことはありますか?これらの一般的な問題により、開発プロセスが遅くなり、イライラしてエラーが発生しやすいコードが生成される可能性があります。

動的レイアウトの導入

実行時にデータに基づいてレイアウトを作成することで、変更に簡単に適応できる、柔軟で保守性が高く、スケーラブルなアプリケーションを構築できます。 動的レイアウト と呼ばれるこのアプローチにより、HTML を繰り返し編集する必要がなくなり、UI がデータとシームレスに同期した状態を維持できるようになります。

この記事では、動的レイアウトが開発ワークフローをどのように変革し、プロジェクトを向上させることができるかを探っていきます。

動的レイアウトを使用する理由

動的レイアウトは、コンテンツが頻繁に変更される場合、または API や他のデータ ソースから取得する、またはユーザー インタラクションに応答する応答性の高い UI を表示する場合に特に有益です。

動的レイアウトの利点

  • 柔軟性 : HTML やテンプレート コードを変更せずに、基礎となるデータに基づいて UI コンポーネントを簡単に調整します。
  • 保守性 : DRY (Don'trepeat Yourself) 原則を遵守し、コードの繰り返しを減らし、保守を簡素化します。
  • スケーラビリティ : UI をプログラムで管理し、項目の簡単な更新、追加、削除を可能にします。
  • エラー削減 : HTML の手動編集を最小限に抑え、エラーの可能性を減らします。
  • 応答性の強化 : 条件に基づいて UI 要素を動的に表示または非表示にし、ユーザー操作やデータ変更に対するインターフェイスの応答性を高めます。

動的レイアウトの実践的なシナリオ

動的レイアウトは、次のような現実世界のさまざまなシナリオで威力を発揮します。

  • フォーム : フォームを多用するアプリの場合、フォーム フィールドを検証ライブラリと組み合わせた計算プロパティに抽象化することが最善の方法かもしれません。レイアウトでは、プロパティをループして、ラベル、クラス名、検証メッセージなどのフォーム フィールドとプロパティを条件付きで表示できます。
  • ブログ投稿リスト : 各ポストカードのコンテンツをデータに基づいて動的に管理および更新します。
  • コンテンツ ブロック : 多様なコンテンツ要素を効率的に整理して表示します。
  • ユーザー リスト、ナビゲーション アイテム、ダッシュボード パネル : HTML を手動で更新しなくても、一貫したスタイルと簡単な調整が保証されます。
  • Web サイトのセクション : セクションを動的に生成して、一貫性のある簡単に調整可能なレイアウトを維持します。

これらの要素を動的に生成することで、一貫性を確保し、調整を簡素化し、クリーンなコードベースを維持します。

動的ナビゲーションバーの構築

動的ナビゲーションバーを構築して、動的レイアウトを実際に体験してみましょう。参考までに、このチュートリアルの 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. 蛍光体アイコン Vue — アイコン コンポーネント

静的アプローチ

静的 Navbar コンポーネントには多数の 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. Bestehende Projekte umgestalten: Identifizieren und umgestalten Sie Teile Ihrer aktuellen Projekte, bei denen dynamische Layouts die Effizienz und Lesbarkeit verbessern können, insbesondere in Bereichen mit sich wiederholendem HTML oder Komponentenlogik.
  2. Integration mit CMS: Experimentieren Sie mit der Integration eines CMS oder anderer Systeme in Ihre dynamischen Layouts, um noch dynamischere und reaktionsfähigere Benutzeroberflächen zu erstellen.
  3. Arbeiten Sie mit Ihrem Team zusammen: Teilen Sie Ihre Erkenntnisse zu dynamischen Layouts mit Ihrem Team. Besprechen Sie, wie Sie gemeinsam dynamische Layouts in Ihren Projekten nutzen können, um die Produktivität zu steigern und eine Kultur der kontinuierlichen Verbesserung zu fördern.
  4. Erweiterte Anwendungsfälle erkunden: Erkunden Sie weiterhin fortgeschrittenere Anwendungen dynamischer Layouts. Meisterschaft entsteht durch konsequentes Üben und Erforschen.

Mit diesen Schritten sind Sie auf dem besten Weg, sich mit dynamischen Layouts vertraut zu machen. Für ein noch reibungsloseres Erlebnis beim Erstellen dynamischer Schnittstellen schauen Sie sich unseren Kurs über einfache Schnittstellen mit Vuetify an, der beliebten Komponentenbibliothek für Vue.js-Entwickler.

Durch die Einführung dynamischer Layouts können Sie Ihren Entwicklungsprozess optimieren, die Flexibilität Ihrer Anwendung erhöhen und eine sauberere, besser wartbare Codebasis beibehalten. Beginnen Sie noch heute mit der Integration dynamischer Layouts in Ihre Projekte und erleben Sie die transformative Wirkung auf Ihren Workflow und Ihre Anwendungsqualität.

Ursprünglich veröffentlicht unter https://www.vuemastery.com am 5. September 2024.


以上がVue jsx を使用した動的レイアウト: 柔軟で保守可能な UI のガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
ブラウザを超えて:現実世界のJavaScriptブラウザを超えて:現実世界のJavaScriptApr 12, 2025 am 12:06 AM

現実世界におけるJavaScriptのアプリケーションには、サーバー側のプログラミング、モバイルアプリケーション開発、モノのインターネット制御が含まれます。 2。モバイルアプリケーションの開発は、ReactNativeを通じて実行され、クロスプラットフォームの展開をサポートします。 3.ハードウェアの相互作用に適したJohnny-Fiveライブラリを介したIoTデバイス制御に使用されます。

next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合)next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合)Apr 11, 2025 am 08:23 AM

私はあなたの日常的な技術ツールを使用して機能的なマルチテナントSaaSアプリケーション(EDTECHアプリ)を作成しましたが、あなたは同じことをすることができます。 まず、マルチテナントSaaSアプリケーションとは何ですか? マルチテナントSaaSアプリケーションを使用すると、Singの複数の顧客にサービスを提供できます

next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合)next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合)Apr 11, 2025 am 08:22 AM

この記事では、許可によって保護されたバックエンドとのフロントエンド統合を示し、next.jsを使用して機能的なedtech SaaSアプリケーションを構築します。 FrontEndはユーザーのアクセス許可を取得してUIの可視性を制御し、APIリクエストがロールベースに付着することを保証します

JavaScript:Web言語の汎用性の調査JavaScript:Web言語の汎用性の調査Apr 11, 2025 am 12:01 AM

JavaScriptは、現代のWeb開発のコア言語であり、その多様性と柔軟性に広く使用されています。 1)フロントエンド開発:DOM操作と最新のフレームワーク(React、Vue.JS、Angularなど)を通じて、動的なWebページとシングルページアプリケーションを構築します。 2)サーバー側の開発:node.jsは、非ブロッキングI/Oモデルを使用して、高い並行性とリアルタイムアプリケーションを処理します。 3)モバイルおよびデスクトップアプリケーション開発:クロスプラットフォーム開発は、反応および電子を通じて実現され、開発効率を向上させます。

JavaScriptの進化:現在の傾向と将来の見通しJavaScriptの進化:現在の傾向と将来の見通しApr 10, 2025 am 09:33 AM

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

javascriptの分解:それが何をするのか、なぜそれが重要なのかjavascriptの分解:それが何をするのか、なぜそれが重要なのかApr 09, 2025 am 12:07 AM

JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

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 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。