ihojmanb
ihojmanb

Reputation: 482

I want to change Vue components with media Queries

In my App.vue I've set my template like this

<app-header></app-header>
<router-view></router-view>
<app-footer ></app-footer>

app-header sets a header component to every other component of my project (so I don't have to repeat myself). app-footer does the same, but with a common footer for all of my components.

This works perfect with my Desktop web, but for Mobile I would like to change the header component to a new-header.vuecomponent, and I would like to get rid of the Footer when using a mobile device so it doesn't use screenspace.

How can I achieve this? I tried to use app-footer {display: none;} in a media query at App.Vue but its not working.

Upvotes: 0

Views: 5063

Answers (1)

Steven Spungin
Steven Spungin

Reputation: 29109

You do not want to use CSS to hide. The beauty of Vue is that in the case of mobile, the code will not even be generated at all.

Use a v-if directive, and add an isMobile property to your data, computed, store, etc. Or call a method to get it.

<app-footer v-if='!isMobile'></app-footer>

For the header, there are 2 ways. Using a component element with v-bind:is to swap in the correct one, or using v-if and v-else

<app-header v-if='!isMobile'></app-header>
<app-header-mobile v-else></app-header-mobile>

Here is the official link to the Vue dynamic component approach. https://v2.vuejs.org/v2/guide/components-dynamic-async.html.

It would look like this:

 <component v-bind:is="currentHeaderComponent"></component>

In this case, you would set currentHeaderComponent based on your conditions.

If you insist on CSS and media queries for the footer, set the component id or class, and that in your CSS

Component

<app-header id='app-header'></app-header>
<router-view></router-view>
<app-footer id='app-footer'></app-footer>

CSS

#app-footer {display: none;}

Upvotes: 3

Related Questions