我正在使用Enquire.js和Vue.js进行媒体查询。当我手动调整浏览器窗口的大小时,这一切都非常有效。但是,我在文档加载方面没有得到匹配,这是一种奇怪的行为,在打开Chrome 的切换设备模式或在手机上访问网站时最为明显。我检查了“匹配和不匹配示例”,它在所述模式下或使用手机访问时按预期工作。我想知道Vue.js和Enquire.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
)都没有运气。