Chris
Chris

Reputation: 14208

vue binding value based on media query

carousel-3d(:display="3", :width="150", :height="150")

I want to set the attribute bindings based on a media query

e.g.

display should become 5 when screen width > 960px

Upvotes: 15

Views: 27232

Answers (2)

HalfWebDev
HalfWebDev

Reputation: 7648

I struggled to find any solutions with Vuejs alone myself or if at all that are there, are already too complex. Involves a lot of unnecessary work where things can be done neatly and in CSS.

That solution is styled components or for a matter of fact any CSS in JS solutions to handle such things with ease.

For example in styled components your styles are written inside ES6 template literal.

import styled from 'styled-components';
import breakpoint from '../utils/breakpoint.js';

const YourStyledComponent = styled.div`
    width: calc(100% - 30px);
    @media (min-width: ${breakpoint.SM}px) {
        // Your media styles
    }
`;

Then inside your Vue component use it as a normal component. You can pass it props as well. Do read more about it - Vue-styled-components.

Doing this way you are using just CSS for styling everything. It's a must for front-end development considering the performance. I think it's a long time since we stopped adding eventListeners to Javascript related to styling or handling layout.

Upvotes: 1

Steve Holgado
Steve Holgado

Reputation: 12071

You could try binding the display value to a component property:

<carousel-3d :display="display">

...and then update that property on window resize:

...

data() {
  return {
    display: 3
  }
},

methods: {
  onResize() {
    if (window.innerWidth > 960) {
      this.display = 5
    } else {
      this.display = 3
    }
  }
},

created() {
  window.addEventListener('resize', this.onResize)
},

beforeDestroy() {
  window.removeEventListener('resize', this.onResize)
},

...

Upvotes: 20

Related Questions