用 Vue.js 编写基于元素的响应式组件

CSS 媒体查询很棒,它们允许您根据浏览器视图端口的大小更改组件的风格,但它们并不总是你需要的。有时你希望根据组件本身的宽度而不是窗口的宽度来更改组件的风格。现在,你可以等到 CSS 元素查询最终将其变成某些最终的规格,并在永久绿色浏览器中发送,但对于 Vue.js 组件来说,需要更少的等待的解决方案: vue-responsive-component

本指南假定您已经设置了 Vue.js 项目,否则继续使用 vue-cli 3.0启动新的 Vue 项目,并且默认选项。

安装视觉响应组件

「vue-responsive-components」是一个使用ResizeObserver(通过基于MutationObserver的多元文件)的库,以便有效地确定一个元素何时变大。

1$ npm install --save vue-responsive-components

响应组件

让我们继续在我们的组件目录中创建一个名为Responsive.vue的文件。

 1[label components/Responsive.vue]
 2<template>
 3  <!--
 4    v-responsive takes a set of objects
 5    where the keys are class names and the values are
 6    functions that take an element and return a boolean.
 7    If the functions return true, then the classes will be applied.
 8
 9    In this case, if the component is less than 800 pixels wide,
10    the `small` class will be applied.
11    If the component is less than 400 pixels wide, both the `small`
12    and `tiny` classes will be applied.
13  -->
14  <div class="responsive-component" v-responsive="{
15    tiny: el => el.width < 400,
16    small: el => el.width < 800
17  }">
18  </div>
19</template>
20
21<script>
22import { ResponsiveDirective } from "vue-responsive-components"
23
24export default {
25  directives: {
26    responsive: ResponsiveDirective
27  }
28}
29</script>
30
31<style scoped>
32.responsive-component {
33  height: 200px;
34  background: red;
35}
36
37/* Applied when the component is less than 800px wide. */
38.responsive-component.small {
39  background: green;
40}
41
42/* Applied when the component is less than 400px wide. */
43.responsive-component.tiny {
44  background: blue;
45}
46</style>

它只会是一个大红色盒子,除非元素大小小小于800像素,在这种情况下它将是一个绿色盒子,如果它得到任何更小的,比如400像素,它将是一个蓝色盒子。

当然,由于每个查询都具有一个函数作为一个论点,您可以使用它们做更先进的事情。

那么,我们如何测试我们的组件?

继续打开App.vue(或您想要嵌入响应组件的任何组件)

 1[label App.vue]
 2<template>
 3  <!--
 4    This gives us convenient resize handles to shrink and resize
 5    the parent of the responsive component.
 6  -->
 7  <div id="app" style="resize: horizontal; overflow: hidden;">
 8    <Responsive></Responsive>
 9  </div>
10</template>
11
12<script>
13import Responsive from './components/Responsive.vue'
14
15export default {
16  components: {
17    Responsive
18  }
19}
20</script>

现在,您应该发现您的彩色组件盒(component-thingy)将在您调整主组件大小时改变颜色。

这可以用于各种各样的东西!列表卡动态适应他们的环境,无论他们的布局,等等!使用你的想象力!

有关视觉响应组件的更多信息,请参阅 官方文件

Published At
Categories with 技术
Tagged with
comments powered by Disqus