如何在屏幕大小更改时更改vue.js数据值?

时间:2018-03-21 19:05:59

标签: 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
            }
});

我正在寻找一种方法来在(最大宽度:547px)的屏幕断点变为活动状态时更改“移动”的值。并在此移动断点变为非活动状态时将其更改回来(屏幕超过547px)。我通常使用skel(https://github.com/ajlkn/skel)来处理屏幕断点,但是我无法从Vue内部访问skel,反之亦然。我会放弃使用Vue执行此特定任务,但显示:none,并且display:block抛出我的演示文稿 - 将我的元素转换为块。

3 个答案:

答案 0 :(得分:1)

检查此库: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>

或只是使用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;
    }
}
当然,由你决定要在什么断点上显示什么和隐藏什么,我希望这会有所帮助。

答案 1 :(得分:1)

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

computed: {
  mobile() {
    return this.$vuetify.breakpoint.sm
  },
}
屏幕宽度小于600像素时,

mobile将会更改为true

您的代码将是这样的(我也将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>

答案 2 :(得分:0)

您可以使用以下onorientationchange事件:

methods: {
  detectOrientationChange() {
   switch(window.orientation) {  
      case -90 || 90:
        // landscape
      this.mobile = false;
      break; 
      default:
        // portrait
        this.mobile = true;
        break; 
    }
  }
},
mounted() {
  this.$nextTick(()=>{
    window.addEventListener('onorientationchange', this.detectOrientationChange)
  }
},
created() {
  this.detectOrientationChange(); // when instance is created
}
相关问题