I used these 9 tips to package Vue components, and the boss praised me as ‘well sealed’


Search [Great Move to the World] on WeChat, and I will share with you the front-end industry trends, learning paths, etc. as soon as possible.
This articleGitHubhttps://github.com/qq449245884/xiaozhiIt has been included, and there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

Components are the basic building blocks of front-end frameworks. Designing them better will make our applications easier to change and understand. In this session, share nine tips you’ve learned on the job over the past few years.

1. You probably don’t need to create a component

Before creating a component, see if it’s for reusability and adding a state to some UI, or just to organize and divide code.

If the latter, then you don’t need to create it as it just adds more unnecessary work like passingpropsand launch events.

Not only that, but it requires us to jump to that file to see what it contains instead of seeing it directly in the parent component, which is much cleaner.

2. Use slots instead of props to display content

Suppose there is a reusable button component that passespropsGet the text.

<BaseButton label="Delete Item"/>

If you want to show an icon in it, you have to add more props like<BaseButton label="Delete Item" icon="delete" />and update the component to display the icon.

But with slots, we can display the label the way we want every time the component is used:

  Delete Item <Icon name="delete" />

Or you just need to make a certain word bold. For slots, you can use directly in the text<strong>markup instead of parsing it in the component.

3. Group the component with what triggers it

Sometimes two separate components are used together in a certain situation. It’s better to put them in a new component so it’s easier to reuse and move them around.

A common example isModalcomponents. We usually display when a specific button is clickedModal. Instead of addingshowModalState and import the modal with its button, it’s better to have a single component that displays the button, and when the user clicks it, it displays the associated modal.

<!-- CreateItemButton.vue -->
  <Modal v-if="showModal" @close="showModal = false" />
  <BaseButton @click="showModal = true">
    Create Item

<script setup>
const showModal = false

4. Using teleport, display fixed position elements from anywhere

Continuing with the previous example, if we want to display the modal properly, we need to make sure the modal uses the correctz-index, and it appears in the correct place in the HTML code, so it always appears on top of everything on the page.

We can do this by displaying the modal directly as<body>element to easily avoid this problem wherever we use it in the component structure.

Teleport componentenables us to do this.

All we have to do is use<Teleport to="body">to wrap the modal component.

<!-- BaseModal.vue -->
  <Teleport to="body">
    <div class="modal"></div>

This component is part of Vue 3 built-in components. If you’re using Vue 2, check outPortalVue

5. Group related props in one object

A component’s prop list is a major part of a component’s interface. The clearer the interface, the easier it is to use and reason about.

ImprovepropOne approach to lists is to group related properties together. Take this component as an example:

  <!-- more props -->

It takes a few seconds for us to understand what are thepropsRelated to posts. But we can put the post relatedpropsgrouped to make it clearer.

<PostCard :post="post" :layout="currentLayout" />

So now we know very quickly,layoutnopostpart of the data.

Not only that, but we also use this method to update thepropsmade easier. E.g,Add or remove props related to the post, without requiring us to update the component’spropslist.

6. Give each loop item its own state

A good reason to create a new component is to provide a piece of user interface with its own state. A common place where we need to do this is in thev-forIn the loop:

    <div v-for="(item, index) in items" :key="item.id">
      <input type="checkbox" v-model="checkedItems[index]">
<script setup>
const checkedItems = ref(items.map(item => item.checked))

checked for trackingitems, we have to create an array and useitemsThe initial value to fill it. But this code is not powerful enough. To make it better, we have to makeitemsthrough theiridinstead ofindex to visit becauseindexis unreliable and can change. For example, what if you add a feature that supports dragging and dropping to rearrange items?

To simplify this code, we can introduce a new component for eachitemSave a state. like this:

    <Item v-for="item in items" :key="item.id" :item="item" />

ItemThe component content is as follows:

    <input type="checkbox" v-model="checked">

<script setup>
const props = defineProps({ item: Object })
const checked = ref(props.item.checked)

Another benefit of this approach is that we add all item-related data, computed properties, and methods in one place, which is easy to understand and change.

7. Move loading data as close to its UI as possible

Whether you’re loading it with GraphQL or another API, it’s best to place your code as close as possible to the user interface that uses it. There are two reasons for this:

  1. Moving UI components with data just got easier. Just move that component without looking for its dependencies.
  2. It’s always easier to understand code when all the pieces are in one place – you can see where the UI and its data come from.

Sometimes, multiple components use the same fetched data. In this case, the fetched code can be moved up one level. So, there would be a parent component, where the data is fetched, and a child component, where the data would be passed to it.

But make sure it’s a single layer. If not, then look for a way to improve your component design and the relationships between them.

8. Pure UI components should not access application state

There are two types of front-end components: pure UI components and application-specific components.

Pure UI components are like buttons, input boxes, etc. They should not know anything about the application. Their job is just to display UI – they get data through props.

Application-specific components are components that are aware of the state of the application, either local or global (via a state management library such as Pinia).

Separating these components makes it easier to reuse UI components elsewhere in the application, or even in other applications.

This trick also works if you’re building your own UI components. If you are using an external library such asVuetifyor Quasar, then you don’t have to worry about that – the components are designed with that in mind.

9. Do not specify width or margin in components

When creating a component, you should think of it as a piece of UI that can be used like any other native element.

Letting the user specify the space around a component is a great way to achieve this.

Say your component has a top margin on its root element, and the user wants to display it below some element, but without a top margin. To do this, the user must set amarginsame negativemargin,for examplemargin-top: -50px;Not to mention that in some cases the user has to match the specificity of the selector (or possibly use!important)。

And the same goes for width. If users want this component to be responsive, they must override its width and max-width.

So it makes sense to always give the user this control by not setting the width and margins inside the component.

The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool for everyone.Fundebug



Have dreams, have dry goods, WeChat search【Great move to the world】Pay attention to this dishwashing wisdom who is still washing dishes in the early morning.

This articleGitHubhttps://github.com/qq449245884/xiaozhiIt has been included, and there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

I used these 9 tips to package Vue components, and the boss praised me as 'well sealed'

Recommended Today

Redis Lua Tutorial

lua–redis Introduction Using Lua scripts in Redis is a relatively common thing in business development.Advantages of using LuaThere are the following points. For sending multiple redis commands, use Lua scripts toReduce network overhead. It is especially critical when the network transmission is slow or the response requirements are high.Lua scripts can process multiple requests at […]