屏幕尺寸变化时如何更改 vue.js 数据值?

Wil*_*ore 5 javascript vue.js skel

<div id="app">
    <ul>
        <!-- On mobile devices use short heading -->
        <template v-if="mobile == 1">
            <li><a href="#">Heading</a></li>
        </template>
        <!-- Else use long heading -->
        <template v-else-if="mobile == 0">
            <li><a href="#">Heading Long</a></li>
        </template>
    </ul>
</div>

<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<script>
    var app = new Vue({
            el: '#app',
            data: {
                mobile: 0
            }
});
Run Code Online (Sandbox Code Playgroud)

当 (max-width: 547px) 的屏幕断点变为活动时,我正在寻找一种方法来更改 'mobile' 的值。并在此移动断点变为非活动状态(屏幕超过 547 像素)时将其更改回来。我通常使用 skel ( https://github.com/ajlkn/skel ) 来处理屏幕断点,但我无法从 Vue 内部访问 skel,反之亦然。我会放弃使用 Vue 来完成这个特定的任务,但是 display: none 和 display: block 会破坏我的演示文稿——将我的元素变成一个块。

use*_*641 5

如果您使用的是Vuetify,则可以根据breakpointsxs、sm、md、lg、xl(在Material Design 中指定)的内置值以编程方式调整数据值,如下所示:

computed: {
  mobile() {
    return this.$vuetify.breakpoint.sm
  },
}
Run Code Online (Sandbox Code Playgroud)

mobiletrue屏幕宽度小于 600px 时将变为。

您的代码将是这样的(我还将if语句直接移到<li>元素上):

<div id="app">
    <ul>
        <!-- On mobile devices use short heading -->
        <li v-if="mobile"><a href="#">Heading</a></li>
        <!-- Else use long heading -->
        <li v-else><a href="#">Heading Long</a></li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)


Tak*_*aki 2

检查这个库: https: //github.com/apertureless/vue-breakpoints

<div id="app">
    <ul>
        <!-- On mobile devices use short heading -->
        <hide-at breakpoint="medium">
        <template v-if="mobile == 1">
            <li><a href="#">Heading</a></li>
        </template>
        </hide-at>
        <!-- Else use long heading -->
        <show-at breakpoint="mediumAndAbove">
        <template v-else-if="mobile == 0">
            <li><a href="#">Heading Long</a></li>
        </template>
        </show-at>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

或者简单地选择media querieshttps://www.w3schools.com/css/css3_mediaqueries_ex.asp

CSS:

@media screen and (max-width: 600px) {
    #app ul il:first-of-type {
        visibility: visible;
    }
    #app ul il:last-of-type {
        visibility: hidden;
    }
}


@media screen and (max-width: 992px) {
    #app ul il:first-of-type {
        visibility: hidden;
    }
    #app ul il:last-of-type {
        visibility: visible;
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,由您决定在什么断点上显示什么和隐藏什么,我希望这会有所帮助。