Vue.jsで要素ベースのレスポンシブコンポーネントを作成する
CSSメディアクエリは素晴らしいです。 ブラウザのビューポートのサイズに基づいて、コンポーネントのスタイルを変更できます。 しかし、それらは必ずしもあなたが必要とするものではありません。 ウィンドウの幅ではなく、コンポーネント自体の幅に基づいてコンポーネントのスタイルを変更したい場合があります。 これで、CSS Element Queriesが最終的に最終的な仕様になり、常緑のブラウザーで出荷されるまで待つことができますが、Vue.jsコンポーネントには、はるかに少ない待機時間を必要とするはるかに簡単なソリューションがあります:
このガイドは、Vue.jsプロジェクトがすでに設定されていることを前提としています。 そうでない場合は、先に進み、 vue-cli3.0とデフォルトのオプションを使用して新しいVueプロジェクトを開始します。 $ vue create my-new-project
Enterキーを数回押すだけで十分です。
vue-sensitive-componentsをインストールします
vue-responsive-components
は、 ResizeObserver ( MutationObserver ベースのポリフィルを介して)を使用して、要素のサイズがいつ変更されるかをパフォーマンス的に判断するライブラリです。 さあ、今すぐライブラリを入手してください。
$ npm install --save vue-responsive-components
レスポンシブコンポーネント
先に進んで、というファイルを作成しましょう Responsive.vue
コンポーネントディレクトリにあります。 はい、それは私が考えることができる最も創造的な名前についてです。
<template>
<!--
v-responsive takes a set of objects
where the keys are class names and the values are
functions that take an element and return a boolean.
If the functions return true, then the classes will be applied.
In this case, if the component is less than 800 pixels wide,
the `small` class will be applied.
If the component is less than 400 pixels wide, both the `small`
and `tiny` classes will be applied.
-->
<div class="responsive-component" v-responsive="{
tiny: el => el.width < 400,
small: el => el.width < 800
}">
</div>
</template>
<script>
import { ResponsiveDirective } from "vue-responsive-components"
export default {
directives: {
responsive: ResponsiveDirective
}
}
</script>
<style scoped>
.responsive-component {
height: 200px;
background: red;
}
/* Applied when the component is less than 800px wide. */
.responsive-component.small {
background: green;
}
/* Applied when the component is less than 400px wide. */
.responsive-component.tiny {
background: blue;
}
</style>
了解しました。これは、世界で最も退屈なコンポーネントです。 要素のサイズが800ピクセル未満でない限り、これは大きな赤いボックスになります。800ピクセル未満の場合は緑色のボックスになり、さらに小さくなった場合、たとえば400ピクセルの場合は青いボックスになります。 イッピー。
もちろん、これらの各クエリは引数として関数を受け取るため、それらを使用してはるかに高度なことを行うことができます。
では…コンポーネントをどのようにテストしますか?
さあ、開いてください App.vue
(またはレスポンシブコンポーネントを内部に埋め込みたいコンポーネント)
<template>
<!--
This gives us convenient resize handles to shrink and resize
the parent of the responsive component.
-->
<div id="app" style="resize: horizontal; overflow: hidden;">
<Responsive></Responsive>
</div>
</template>
<script>
import Responsive from './components/Responsive.vue'
export default {
components: {
Responsive
}
}
</script>
これで、色付きのボックスコンポーネントが、親コンポーネントのサイズを変更すると色が変わることがわかります。
これはあらゆる種類のものに使用できます! レイアウトに関係なく、環境に動的に適応するカードなどをリストアップしてください。 想像力を使って!
vue-sensitive-componentsの詳細については、公式ドキュメントを参照してください。