【问题标题】:Add class only on mobile - Vuejs and bootstrap仅在移动设备上添加类 - Vuejs 和引导程序
【发布时间】:2019-04-21 00:27:11
【问题描述】:

我只想在移动设备上添加课程。我在使用 vuetify 之前已经这样做了,但是使用 vue 似乎更困难:

代码:

<div class="{'mobileSnackBar': breakpoint.xs}">
  <p> This is my snackbar </p>
</div>

在 vuetify 中你有 $vuetify.breakpoint.xs 但是我如何使用引导程序获得类似的效果?或者请推荐一个替代方案。

【问题讨论】:

  • 你为什么不使用 CSS 媒体查询?
  • 好吧,因为有了 vuetify,这个方法就干净多了。因此,我正在寻找类似的替代方案
  • 将 JS 用于自然的 CSS 工作永远不会“更干净”。反之亦然。
  • 你尝试过 Vue sn-p 吗?

标签: vue.js vuejs2 bootstrap-4


【解决方案1】:

使用 vuetify 你可以做到:

computed: {
    is_screen_small() {
        return this.$vuetify.breakpoint.smOnly
    },
}

然后像这样组合起来:

<div class="{'mobileSnackBar': is_screen_small}">
  <p> This is my snackbar </p>
</div>

请务必阅读 breakpoints 的 vuetify 文档以了解更多信息。

但是据我所知,使用引导程序的唯一方法是使用媒体查询:

// Small devices 
@media (max-width: 760px) { 
  //Add your style here
 }

虽然,有一个与引导无关的解决方案:

computed: {
  is_mobile() {
    const isMobile = window.matchMedia("only screen and (max-width: 760px)")
    return isMobile.matches ? true : false
  }
}

然后像这样组合起来:

<div class="{'mobileSnackBar': is_mobile}">
  <p> This is my snackbar </p>
</div>

【讨论】:

  • 不幸的是,按屏幕大小进行操作并不能保证您使用的是带有触摸功能的移动设备。如果你把你的桌面屏幕缩小到足够大,它就会认为它是移动的。所以你需要小心一点,特别是如果你需要捕获鼠标事件,例如鼠标悬停或鼠标离开。此外,现在有些电脑有触摸屏,所以鼠标和触摸事件都可以触发......这有点雷区。
【解决方案2】:

引导程序的另一种方法是使用断点类来显示/隐藏元素,如下所示:

<div class="mobileSnackBar d-sm-none">
   <p> This is my snackbar </p>
</div>
<div class="d-none d-sm-block">
   <p> This is my snackbar </p>
</div>

使用组件而不是 html 更有意义,即使这样也可能不是最干净的解决方案,但它确实有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多