使用 Enquire.js 和 Vue.js 来查询浏览器的大小
Using Enquire.js with Vue.js to query about the browser's size
我正在使用 Enquire.js 和 Vue.js 来查询浏览器的大小并相应地更新两个数据属性。所以,如果我这样做:
ready: function() {
// Listen for changes in the browser's size
window.addEventListener("resize",
enquire.register("screen and (max-width:400px)", {
match: function() {
this.displayIsLarge = false;
this.displayIsSmall = true;
console.log("the screen is now small");
},
unmatch: function() {
this.displayIsLarge = true;
this.displayIsSmall = false;
console.log("the screen is now large");
}
})
);
}
它将在控制台 (jsfiddle here) 中输出正确的消息,但是它不会更改 displayIsLarge
和 displayIsSmall
的值。我在这里错过了什么?
问题出在 this
的范围内。完整的工作代码是:
ready: function() {
var self = this;
// Listen for changes in the browser's size
window.addEventListener("resize",
enquire.register("screen and (max-width:400px)", {
match: function() {
self.displayIsSmall = true;
self.displayIsLarge = false;
console.log("the screen is now small");
},
unmatch: function() {
self.displayIsLarge = true;
self.displayIsSmall = false;
console.log("the screen is now large");
}
})
);
}
Jsfiddle here
我正在使用 Enquire.js 和 Vue.js 来查询浏览器的大小并相应地更新两个数据属性。所以,如果我这样做:
ready: function() {
// Listen for changes in the browser's size
window.addEventListener("resize",
enquire.register("screen and (max-width:400px)", {
match: function() {
this.displayIsLarge = false;
this.displayIsSmall = true;
console.log("the screen is now small");
},
unmatch: function() {
this.displayIsLarge = true;
this.displayIsSmall = false;
console.log("the screen is now large");
}
})
);
}
它将在控制台 (jsfiddle here) 中输出正确的消息,但是它不会更改 displayIsLarge
和 displayIsSmall
的值。我在这里错过了什么?
问题出在 this
的范围内。完整的工作代码是:
ready: function() {
var self = this;
// Listen for changes in the browser's size
window.addEventListener("resize",
enquire.register("screen and (max-width:400px)", {
match: function() {
self.displayIsSmall = true;
self.displayIsLarge = false;
console.log("the screen is now small");
},
unmatch: function() {
self.displayIsLarge = true;
self.displayIsSmall = false;
console.log("the screen is now large");
}
})
);
}
Jsfiddle here