LoginSignup
27
21

More than 3 years have passed since last update.

Vue.jsで画面サイズによってClassやidを付与したい

Last updated at Posted at 2019-06-29

どんだけ探しても画面サイズの取得とクラスの付与に関する記事はあるが、なぜかタイトルの記事が無かったから書く

今回やりたいのは画面サイズが800px以下になった時にクラスを付与したい。ってだけ
だからv-ifを使ってコンテンツ非表示とは少し違う。

クラスを付与したいHTML

Test.vue
<!-- ここに800px以下になったら hoge というクラスを付与したい -->
<div>
    <p>これはテストです。</p>
</div>

ぱぱっとコードを先に置いておく

Test.vue
<div v-bind:class="{active:hoge}">
    <p>これはテストです。</p>
</div>

<script>
    export default {
        data() {
            return {
                hoge: {}
            }
        }
    },
    methods: {
        handleResize: function() {
            if (window.innerWidth <= 800) {
                this.hoge = true
            } else {
                this.hoge = false
            }
        }
    },
    created() {
        window.addEventListener('resize', this.handleResize)
        this.handleResize()
        },
    destroyed() {
        window.removeEventListener('resize', this.handleResize)
    }
</script>

クラス付与する部分の説明

ここでv-bindに与えたDOM要素が真の場合ならクラスにhogeが付与されます。

Test.vue
<div v-bind:class="{active:hoge}">
    <p>これはテストです。</p>
</div>

画面サイズによってクラスを付与する処理の説明

ここのメソッドでhandleResizeという関数を作成しています。

window.innerWidthには画面幅サイズが入っているので、それが800px以下ならという分岐をしています。

真ならhogetrueを与えて偽ならhogefalseを与えます。

Test.vue
<script>
    methods: {
        handleResize: function() {
            if (window.innerWidth <= 800) {
                this.hoge = true
            } else {
                this.hoge = false
            }
        }
    }
</script>

画面サイズが変わる毎にイベントを実行したり削除したり

created()でhandleResizeをイベントを実行、destroyedでイベントを削除

Test.vue
<script>
    created() {
        window.addEventListener('resize', this.handleResize)
        this.handleResize()
        },
    destroyed() {
        window.removeEventListener('resize', this.handleResize)
    }
</script>

こうすれば画面サイズが800px以下になった時にhogeというクラスが付与されて、逆に800px以上になった時はクラスが無くなります。

ただもっとスマートなやり方があるはず。。こうした方が良いって意見がある方はコメントお願いします( ◠‿◠ )

27
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
21