G
G
Gravio2019-06-14 19:00:22
JavaScript
Gravio, 2019-06-14 19:00:22

Organizing vue js components?

There is a page with 30 connected components, when a user visits it, we download an array with data from json. From json we get which components we show and which we don’t (via v-if). More or less like this:

<comp1 v-if="(Q === 1 && B === 1) || (Q === 2 && B === 1)"
<comp2 v-if="(Q === 1 && B === 2) || (Q === 2 && B === 2)"
<comp3 v-if="(Q === 1 && B === 3) || (Q === 2 && B === 3)"
<comp4 v-if="(Q === 1 && B === 4) || (Q === 2 && B === 4)"

Is everything implemented correctly? Is it possible to generate components somehow from json ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-06-14
@Gravio

What you have shown looks rather ugly. It can be simplified by adding the component names to an array and adding a computed property:

data: () => ({
  componentNames: [ 'comp1', 'comp2', 'comp3', 'comp4' ],
  ...
}),
computed: {
  componentName() {
    return [ 1, 2 ].includes(this.Q) && this.componentNames[this.B - 1];
  },
},

<component :is="componentName"></component>
UPD. If you additionally need to pass parameters, then instead of component names, you can store objects in the array that will contain the name and set of parameters:
data: () => ({
  components: [
    { name: '...', props: { ... } },
    { name: '...', props: { ... } },
    ...
  ],
  ...
}),

The computed property will not change (except for the name, of course), and the template will look like this:
<component
  v-if="component"
  :is="component.name"
  v-bind="component.props"
></component>

https://jsfiddle.net/69xv0b47/

D
Dima Pautov, 2019-06-14
@bootd

Well, of course, this is not correct, you can get confused. It is better that your json already has some key by which you will display the desired component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question