While static layouts may suffice for simple interfaces, dynamic layouts offer superior maintainability and scalability.

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

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

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

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. Refactor Existing Projects : Identify and refactor parts of your current projects where dynamic layouts can enhance efficiency and readability, especially in areas with repetitive HTML or component logic.
  2. Integrate with CMS : Experiment with integrating a CMS or other systems with your dynamic layouts to create even more dynamic and responsive user interfaces.
  3. Collaborate with Your Team : Share your insights on dynamic layouts with your team. Discuss how you can collectively leverage dynamic layouts in your projects to boost productivity and foster a culture of continuous improvement.
  4. Explore Advanced Use Cases : Continue exploring more advanced applications of dynamic layouts. Mastery comes from consistent practice and exploration.

By taking these steps, you’re well on your way to becoming proficient in dynamic layouts. For an even smoother experience in creating dynamic interfaces, check out our course on Easy Interfaces with Vuetify, the popular component library for Vue.js developers.

By embracing dynamic layouts, you can streamline your development process, enhance your application’s flexibility, and maintain a cleaner, more maintainable codebase. Start integrating dynamic layouts into your projects today and experience the transformative impact on your workflow and application quality.

Originally published at https://www.vuemastery.com on September 5, 2024.


","image":"http://www.luping.net/uploads/20241107/1730940847672c0faf2053f.png","datePublished":"2024-11-08T19:47:47+08:00","dateModified":"2024-11-08T19:47:47+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Dynamic Layouts with Vue jsx: A Guide to Flexible and Maintainable UIs

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

发布于2024-11-08
浏览:658

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

Written by Dubem Izuorah

Have you ever spent hours tweaking the same web layout across multiple pages or struggled to make your UI adapt to changing data without breaking? These common challenges can slow down your development process and lead to frustrating, error-prone code.

Introducing Dynamic Layouts

By creating layouts at runtime based on data, you can build flexible, maintainable, and scalable applications that adapt effortlessly to changes. This approach,called Dynamic layouts , eliminates the need for repetitive HTML edits, allowing your UI to stay in sync with your data seamlessly.

In this article, we’ll explore how dynamic layouts can transform your development workflow and elevate your projects.

Why Use Dynamic Layouts?

Dynamic layouts are particularly beneficial when content frequently changes or when displaying responsive UIs that pull from APIs, other data sources, or respond to user interactions.

Benefits of Dynamic Layouts

  • Flexibility : Easily adjust UI components based on underlying data without modifying HTML or template code.
  • Maintainability : Adhere to the DRY (Don’t Repeat Yourself) principle, reducing repetitive code and simplifying maintenance.
  • Scalability : Manage your UI programmatically, allowing for easy updates, additions, or removals of items.
  • Error Reduction : Minimize manual HTML edits, decreasing the likelihood of errors.
  • Enhanced Responsiveness : Dynamically show or hide UI elements based on conditions, making the interface more responsive to user interactions or data changes.

Practical Scenarios for Dynamic Layouts

Dynamic layouts shine in various real-world scenarios, such as:

  • Forms : For form-heavy apps, it might be best to abstract you form fields into a computed property paired with some validation library. In the layout you can loop through your property to conditionally show form fields and properties like labels, class names, validation messages etc.
  • Blog Post Lists : Manage and update each post card’s content dynamically based on its data.
  • Content Blocks : Organize and display diverse content elements efficiently.
  • User Lists, Navigation Items, Dashboard Panels : Ensure consistent styling and easy adjustments without manual HTML updates.
  • Website Sections : Dynamically generate sections to maintain a cohesive and easily adjustable layout.

By generating these elements dynamically, you ensure consistency, simplify adjustments, and maintain a clean codebase.

Building a Dynamic Navbar

Let’s gain hands-on experience with dynamic layouts by building a dynamic navbar. For reference, here is the Github repo for this tutorial.

Requirements

Imagine you’re developing a payment platform and need to create a clean, extensible navbar component as shown in the screenshots below:

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

Navbar when a user is logged in

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

Navbar with no user logged in

Setting up the Environment

To focus on dynamic layouts, we won’t delve into environment setup details here. You can find the complete code samples in our GitHub repository.

Technologies Used:

  1. Nuxt — Vue framework
  2. Nuxt TailwindCSS — Styling
  3. Phosphor-icons Vue — Icon components

Static Approach

A static Navbar component involves numerous HTML tags and properties, making the code hard to read and maintain.

Updating such a layout is error-prone, especially with repetitive elements sharing the same properties or styling.

While a static approach is useful for drafting layouts, dynamic layouts are preferable for maintainability and collaboration.

Example of a Static Navbar:

? 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>

While static layouts may suffice for simple interfaces, dynamic layouts offer superior maintainability and scalability.

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. Refactor Existing Projects : Identify and refactor parts of your current projects where dynamic layouts can enhance efficiency and readability, especially in areas with repetitive HTML or component logic.
  2. Integrate with CMS : Experiment with integrating a CMS or other systems with your dynamic layouts to create even more dynamic and responsive user interfaces.
  3. Collaborate with Your Team : Share your insights on dynamic layouts with your team. Discuss how you can collectively leverage dynamic layouts in your projects to boost productivity and foster a culture of continuous improvement.
  4. Explore Advanced Use Cases : Continue exploring more advanced applications of dynamic layouts. Mastery comes from consistent practice and exploration.

By taking these steps, you’re well on your way to becoming proficient in dynamic layouts. For an even smoother experience in creating dynamic interfaces, check out our course on Easy Interfaces with Vuetify, the popular component library for Vue.js developers.

By embracing dynamic layouts, you can streamline your development process, enhance your application’s flexibility, and maintain a cleaner, more maintainable codebase. Start integrating dynamic layouts into your projects today and experience the transformative impact on your workflow and application quality.

Originally published at https://www.vuemastery.com on September 5, 2024.


版本声明 本文转载于:https://dev.to/vuemastery/dynamic-layouts-with-vue-jsx-a-guide-to-flexible-and-maintainable-uis-2l57?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 创建信息机器人:初学者指南(HTML/CSS、JavaScript、Gemini API)
    创建信息机器人:初学者指南(HTML/CSS、JavaScript、Gemini API)
    Table of Contents Introduction What is a Chatbot? Understanding the Problem Setting Up the Development Environment Understanding the Problem ...
    编程 发布于2024-11-09
  • Python 中的实例方法与类方法:什么时候应该使用“self”和“cls”?
    Python 中的实例方法与类方法:什么时候应该使用“self”和“cls”?
    深入研究类和实例方法的细微差别:Beyond Self 与 ClsPython 增强提案 (PEP) 8 建议使用“self”作为实例方法中的第一个参数,“cls”作为类方法中的第一个参数。这种区别源于这些方法在处理实例和类时所扮演的不同角色。实例方法:自我优势实例方法在实例的实例上调用班级。它们通...
    编程 发布于2024-11-09
  • 在 Python 中使用 bytes(n) 时,与数字转换的主要区别是什么?
    在 Python 中使用 bytes(n) 时,与数字转换的主要区别是什么?
    Python 中的字节对象:超越数字转换在 Python 中使用字节对象时,必须了解 bytes(n) 是如何转换的函数与数值转换不同。将整数 n 传递给 bytes(n) 不会返回 n 的二进制表示形式,而是创建一个长度为 n 且填充有空字节 (\x00) 的字节字符串。行为背后的基本原理此行为是...
    编程 发布于2024-11-09
  • 如何在 MySQL 中将纪元时间戳转换为人类可读的日期?
    如何在 MySQL 中将纪元时间戳转换为人类可读的日期?
    在 MySQL 中将纪元时间戳转换为人类可读的日期在 MySQL 中,纪元时间戳是日期和时间的数字表示形式。它是自 Unix 纪元(即 1970 年 1 月 1 日 00:00:00 UTC)以来的毫秒数。要将纪元时间戳转换为人类可读的日期,您可以使用 from_unixtime( ) 功能。该函数...
    编程 发布于2024-11-09
  • 如何使用 Pip 获取可用软件包版本列表:综合指南
    如何使用 Pip 获取可用软件包版本列表:综合指南
    如何使用 Pip 获取可用包版本列表:综合指南Pip 是一个广泛使用的 Python 包安装程序,提供了一个安装和管理 Python 包的有效方法。虽然它允许方便地安装特定的软件包版本,但在选择最佳版本之前可能有必要探索所有可能版本的综合列表。本文深入探讨了如何在各种 pip 版本中实现此目的。Pi...
    编程 发布于2024-11-09
  • ## **`std::vector::erase`返回的迭代器在删除后是否指向有效元素?**
    ## **`std::vector::erase`返回的迭代器在删除后是否指向有效元素?**
    std::vector 迭代器失效:详细解释std::vector 中迭代器失效的概念经常被讨论。需要澄清的是,通过 std::vector::erase 擦除向量元素会使严格位于已擦除元素之后的迭代器无效。但是,位于已擦除元素的确切位置的迭代器的有效性仍然不确定。从逻辑上讲,人们可能会假设该迭代器...
    编程 发布于2024-11-09
  • Python 开发人员如何增强调试技术以获得更高效的代码?
    Python 开发人员如何增强调试技术以获得更高效的代码?
    Python 中增强的调试技术增强 Python 中的调试过程对于寻求优化代码的开发人员至关重要。以下是一些帮助您完成此任务的宝贵提示:利用 PDB 模块PDB(Python 调试器)模块提供了全面的调试环境。通过将 pdb.set_trace() 集成到代码中,您可以在特定位置建立断点。这个灵活的...
    编程 发布于2024-11-09
  • AdaBoost - 集成方法,分类:监督机器学习
    AdaBoost - 集成方法,分类:监督机器学习
    Boosting Definition and Purpose Boosting is an ensemble learning technique used in machine learning to improve the accuracy of models...
    编程 发布于2024-11-09
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-11-09
  • 重新学习CS基础知识——实现队列
    重新学习CS基础知识——实现队列
    你曾经站在队列中吗,队列数据结构也做同样的事情。当你想在你最喜欢的自助餐厅点餐时,你站在队伍的最后,然后你就可以继续排队并离开。 CS 中的队列数据结构执行相同的功能。队列数据结构是先进先出的数据结构。队列数据结构可以使用两个基本函数 Enqueue 和 Dequeue 来构建,这两个函数基本上是...
    编程 发布于2024-11-09
  • 为 Angular 18 设置 linter 和 IDE
    为 Angular 18 设置 linter 和 IDE
    将 eslint、prettier、env 添加到应用程序中。 遗憾的是,Angular 默认情况下不会自行生成这一切。更改原理图可以提高数千个 Angular 项目的质量。 设置 eslint 9 连接 eslint: yarn ng add @angular-eslint/sch...
    编程 发布于2024-11-09
  • 使用 JavaScript 进行网页抓取和代理设置的初学者指南
    使用 JavaScript 进行网页抓取和代理设置的初学者指南
    使用JavaScript代码模拟用户操作,获取所需信息。包括模拟用户打开网页、点击链接、输入关键字等操作,并从网页中提取所需信息。 Javascript网页抓取的核心原理 使用JavaScript代码模拟用户操作来获取所需信息。包括模拟用户打开网页、点击链接、输入关键字等操作,并从网...
    编程 发布于2024-11-09
  • 在 Android 上运行 Llama:使用 Ollama 的分步指南
    在 Android 上运行 Llama:使用 Ollama 的分步指南
    Llama 3.2 最近在 Meta 开发者大会上推出,展示了令人印象深刻的多模式功能以及针对使用高通和联发科技硬件的移动设备进行优化的版本。这一突破使开发人员能够在移动设备上运行 Llama 3.2 等强大的 AI 模型,为更高效、私密和响应迅速的 AI 应用程序铺平道路。 Meta 发布了 Ll...
    编程 发布于2024-11-09
  • 如何在 Python 中格式化字符串以将它们对齐直列?
    如何在 Python 中格式化字符串以将它们对齐直列?
    以固定宽度打印字符串打印字符串时,将它们对齐成直列可以增强可读性。在 Python 中使用 format 或 f-string 提供了实现此目的的便捷方法。使用 str.format()str.format() 提供了一种简单的填充方法字符串。其语法包括占位符 {},后跟格式化表达式。对于左对齐,请...
    编程 发布于2024-11-09
  • 为什么微服务比单体架构重要
    为什么微服务比单体架构重要
    在当今快节奏的技术环境中,企业需要可扩展且灵活的解决方案来快速适应不断变化的需求。与传统的整体方法相比,这就是微服务架构的亮点。 1.什么是单体架构? 单体架构是一个单一的、统一的系统,其中所有组件都是互连和相互依赖的。这意味着对系统的任何更改或更新都需要重新构建和重新部署整个应用程...
    编程 发布于2024-11-09

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3