Alpinejs 에서 tailwindcss breakpoint 사용하기 > IT 기술백서

alpine.extend.css

[code]

:root {

    –breakpoint: ‘unset’;

}

@media screen and (min-width: 640px) {

    :root {

        –breakpoint: ‘sm’;

    }

}

@media screen and (min-width: 768px) {

    :root {

        –breakpoint: ‘md’;

    }

}

@media screen and (min-width: 1024px) {

    :root {

        –breakpoint: ‘lg’;

    }

}

@media screen and (min-width: 1280px) {

    :root {

        –breakpoint: ‘xl’;

    }

}

@media screen and (min-width: 1536px) {

    :root {

        –breakpoint: ‘2xl’;

    }

}

[/code]

 

alpine.extends.js

[code]

export default (Alpine) => {

  const breakpoints = [‘unset’, ‘xs’, ‘sm’, ‘md’, ‘lg’, ‘xl’, ‘2xl’, ‘3xl’];

  const getCurrentBreakpoint = () => {

      return getComputedStyle(document.documentElement)

          .getPropertyValue(‘–breakpoint’)

          .trim()

          .replace(/[‘”]+/g, ”)

  }

  Alpine.magic(‘isBreakpoint’, (el) => (breakpoint) => {

          const curBreakpoint = getCurrentBreakpoint();

          const stdIdx = breakpoints.indexOf(breakpoint);

          const curIdx = breakpoints.indexOf(curBreakpoint);

          if (stdIdx <= curIdx) return true;

          return false;

    });

[/code]

 

app.js

[code]

import Alpine from ‘alpinejs’;

import breakpoint from ‘./alpine.extends’;

Alpine.plugin(breakpoint);

window.Alpine = Alpine;

Alpine.start();

[/code]

 

사용법

$isBreakpoint() 함수를 사용할 수 있다.

ex) lg 이상일때 div 보이기

[code]

<div x-show=”show”>메뉴</div>

 

<script type=”text/javascript”>

    window.addEventListener(‘alpine:init’, () => {

        Alpine.data(‘mydata’, () => ({

            show: false,

            init() {

                window.addEventListener(‘resize’, () => { 

                    this.resizeHandler();

                });

                this.resizeHandler();

            },

            resizeHandler() {

                if (this.$isBreakpoint(‘lg’)) {

                    this.show = true;

                } else {

                    this.show = false;

                }

            },

        }));

    });

</script>

[/code]

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

위로 스크롤