DEV Community

Cover image for Vue JS: Generic list
Andrés Baamonde Lozano
Andrés Baamonde Lozano

Posted on

Vue JS: Generic list

During these days i have been working on my personal website. Next step on my pending task list was migrating my current usefull links list to the new website.

But i think that it would be a nice idea making a little component on vue like my previous post. Because a list render is something that i can reuse on a lot of comopnents of my website. This component will be a generic list that delegates item rendering on another component.

My personal website is a functional site so i'm using bootstrap for css dealing. Component will be same apperance and behaviour than current util list on my website.

Alt Text

So, hands on, we start implementation.

Generic list component

This component is simple, it receives a list via props attribute and iterates over it. If there is not any element it show a text. If there are elements it delegates rendering on slot tag.

<template>
  <ul v-if="items.length" class="list-group">
    <li v-for="(item, index) in items" v-bind:key="index" class="list-group-item">
       <slot :item="item"></slot>
    </li>
  </ul>
  <p v-else>This view has no items.</p>
</template>

<script>
export default {
  props: {
    items: Array
  }
}
</script>

<style>
...
</style>

Link item

Item component could be something like this

<template>
<a :href="item.url">
 {{item.url}}
</a>
</template>

<script>
export default {
  props: {
    item: undefined
  }
}
</script>

<style>
...
</style>

Example of use

Okey, i believe you. But how i can use it?

<template>
    <ListContainer :items="links">
      <LinkItem slot-scope="row" :item="row.item"></LinkItem>
    </ListContainer>
</template>

<script>
import ListContainer from '../components/common/ListContainer'
import LinkItem from '../components/utilities/LinkItem'
export default {
  components: {
    ListContainer,
    LinkItem
  }
...
}
</script>
<style>
</style>

Result is the same like my personal website. But this implementation has a advantage. I can reuse my list container in my app only implementing list item render.

Here is a gif showing the component. It works filtering a items list with the form input field.

Example gif search list

References

Top comments (0)