D
D
Dima Pautov2021-10-14 19:29:07
Vue.js
Dima Pautov, 2021-10-14 19:29:07

What is the best way to organize mobile and desktop versions of components in vue?

Hello everyone!))

The task is as follows, there are 2 types of component display, mobile and desktop.
Displaying them depending on the screen size is not a problem.

I was touched by another question, how best to name and display them. The problem is that the desktop component may have more input properties than the mobile component, or they may be completely different.

There are 2 implementation options in my head:
1 Option:

The component itself:

<template>
  <component 
    :is="currentComponent"
    v-bind="$props"
  />
</template>

<script>
export default {
  name: 'MyComponent',
  props: ['prop1',  'prop2',  'prop3',  'prop4'],
  components: {
    DesctopComponent: () => import('./DesctopComponent.vue'),
    MobileComponent: () => import('./MobileComponent.vue')
  },
  computed: {
    currentComponent () {
      return this.mobile
        ? 'MobileComponent'
        : 'DesctopComponent';
    }
  }
}
</script>


Pasting it somewhere:
<template>
  <my-component
    :prop1="value1"
    :prop2="value2"
    :prop3="value3"
    :prop4="value4"
  />
</template>


The problem is that the desktop one has, for example, 4 properties, and the mobile one has 2. + we will need to describe all these properties to the "container" component and pass them through v-bind="$props"

Option 2: In the template itself, where we need to display desired component, we make a condition
<template>
  <desctop-component
    v-if="!mobile"
    :prop1="value1"
    :prop2="value2"
    :prop3="value3"
    :prop4="value4"
  />

  <mobile-component
    v-else
    :prop1="value1"
    :prop2="value2"
  />
</template>


This option saves us from the need for a "container" component and property traversal, but forces us to use the conditional construction again when reusing the component anywhere, which makes "garbage" in templates.

I haven't found any other way yet. Tell me, what other ways are there and which option do you think is better for such tasks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-15
@Aetae

Well, if you optimize, then desctop cannot turn into mobile on the go (it can, of course, but such "experimenters" will not break off reloading the page). In this case: move the exports of such "double" components to a separate file, which immediately upon loading exports the desired variant, without any extra dynamics.
If you do it dynamically, then write a helper function that takes both versions of the component as input and returns an auxiliary functional pass through component that selects the desired one from the two, and simply forwards everything else.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question