Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a list of different component types in Vue

I have a list of objects. Each object contains a type field that is used to determine the component that is needed to be rendered. For example, for paragraph type I would need to render a component named Paragraph. I have roughly a dozen of these different component types.

At the moment I loop through the list in Javascript. I create a div with a random ID and replace that with a Vue component that I create manually using new [ComponentType]({ el: ... }). However, this requires DOM manipulation. Is there a better way that doesn't require manual manipulation of the DOM structure? v-for or similar?

like image 878
MikkoP Avatar asked Dec 09 '16 14:12

MikkoP


People also ask

How do I render components in Vue?

Each Vue component implements a render function. Most of the time, the function will be created by the Vue compiler. When you specify a template on your component, the content of this template will be processed by the Vue compiler that will return a render function.

What is list rendering in VUE JS?

List rendering is one of the most commonly used practices in front-end web development. Dynamic list rendering is often used to present a series of similarly grouped information in a concise and friendly format to the user.

How do I pass data from one component to another component in Vue?

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!

What are the 3 parts of a component in Vue?

Components in Vue are composed of three parts; a template (which is like HTML), styles and JavaScript. These can be split into multiple files or the same .


1 Answers

Yes there is a better way. Use Dynamic Components.

Here's an example shown in those docs.

var vm = new Vue({
  el: '#example',
  data: {
    currentView: 'home'
  },
  components: {
    home: { /* ... */ },
    posts: { /* ... */ },
    archive: { /* ... */ }
  }
})    

<component v-bind:is="currentView">
  <!-- component changes when vm.currentView changes! -->
</component>    
like image 102
Chris Avatar answered Oct 05 '22 13:10

Chris