3

我正在使用Enquire.jsVue.js进行媒体查询。当我手动调整浏览器窗口的大小时,这一切都非常有效。但是,我在文档加载方面没有得到匹配,这是一种奇怪的行为,在打开Chrome 的切换设备模式或在手机上访问网站时最为明显。我检查了“匹配和不匹配示例”,它在所述模式下或使用手机访问时按预期工作。我想知道Vue.jsEnquire.js之间是否存在某种不兼容,或者我做错了什么?

媒体查询的逻辑在我的 vue 实例的 ready 钩子上:

ready:
    function () {
        var self = this;
        enquire.register("screen and (max-width: 400px)", {
            match: function () {
                self.displayIsLarge = false;
                self.displayIsSmall = true;
            },
            unmatch: function () {
                self.displayIsLarge = true;
                self.displayIsSmall = false;
            }
        })
    );

在我的 vue 实例上,我有以下数据属性:

var menu = new Vue({
el: '#app',
data: {
    displayIsLarge: true,
    displayIsSmall: false,

在我的 html 文件中,我使用v-if="displayIsSmall"andv-if="displayIsLarge"来根据浏览器的大小隐藏/显示元素。JsdFiddle在这里

与此同时,我想到,我也许可以通过Setup回调解决这个问题,也许有条件,像这样:

enquire.register("screen and (max-width: 400px)", {
    setup: function() {
        if (this.match) {
            self.displayIsSmall = true;
        }
        else {
            self.displayIsSmall = false;
        }
    },
    match: function () {
        self.displayIsLarge = false;
        self.displayIsSmall = true;
    },
    unmatch: function () {
        self.displayIsLarge = true;
        self.displayIsSmall = false;
    }
})

这没有按预期工作。我错过了什么?JsdFiddle在这里


更新

Vue 的beforeCompile创建的钩子(而不是ready)都没有运气。

4

2 回答 2

3

unmatch唯一发生的情况是从matchunmatch。因此它不会发生,直到你低于 400 像素然后再回到它上面。我建议您采用移动优先的方法,并改为执行类似的操作。

new Vue({
  el: '#app',
  data: {
    displayIsLarge: false,
    displayIsSmall: true
  },
  ready: function () {
    var self = this;
    enquire.register("screen and (min-width: 400px)", {
        match: function () {
            self.displayIsLarge = true;
            self.displayIsSmall = false;
        },
        unmatch: function () {
            self.displayIsLarge = false;
            self.displayIsSmall = true;
        }
    })
  }
})

这是一个小演示:https ://jsfiddle.net/crswll/uc7gaec0/

但是,根据这些元素实际包含和/或执行的内容,使用 CSS 在视觉上切换它们可能更有意义。不过,你比我更清楚发生了什么。

于 2016-03-31T21:09:44.563 回答
0

除了确保我match在页面加载并且不仅在调整大小之后(如上面的答案中详述)之外,我还必须<meta>在我的index.html. 例如,添加以下元标记将强制视口缩放到设备的尺寸,现在呈现正确的样式(即移动):

<meta name="viewport" content="width=device-width, initial-scale=1">

width=device-width在页面宽度与设备宽度之间进行等效,而initial-scale=1将在页面加载时设置初始缩放。

更多细节在这里

于 2016-04-02T16:47:09.340 回答