I sometimes need to change the viewport based on the screen size when loaded, so I'm writing this down as a memo.
CHANGING META TAGS AND VIEWPORT BASED ON SCREEN SIZE
export default {
created() {
this.setViewport();
},
methods: {
setViewport: function() {
let changeWindowSize = 375
let viewportContent = "width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"
if (window.innerWidth < changeWindowSize ) {
viewportContent = "width=375,user-scalable=no,viewport-fit=cover"
}
document.querySelector("meta[name='viewport']").setAttribute("content", viewportContent)
}
}
}Simply put, it gets the screen size using `window.innerWidth` and changes the value to be set for the viewport.
The attributes are set using `document.querySelector`.
ADDENDUM: DETECTING AND CHANGING UPON SCREEN SIZE MODIFICATION
If you want to change the viewport in response to a user's window size change, rather than just on initial load.
export default {
created() {
//window変更を検知
window.addEventListener('resize', this.setViewport)
this.setViewport();
},
beforeDestroy() {
window.removeEventListener('resize', this.setViewport)
},
methods: {
setViewport: function() {
let changeWindowSize = 375
let viewportContent = "width=device-width,initial-scale=1.0"
if (window.innerWidth < changeWindowSize) {
viewportContent = "width=375,user-scalable=no,viewport-fit=cover"
}
document.querySelector("meta[name='viewport']").setAttribute("content", viewportContent)
}
}
}It detects screen size changes using `window.addEventListener` and calls the function.
Detecting screen size changes and calling a function is a pattern you might use quite often.
*As of June 13, 2020: There was a bug where resizing was continuously detected when the display size was magnified in Windows 10, for some reason.
RECOMMENDED VUE.JS BOOKS
I tend to read books, but I truly feel that I learn more deeply when I implement things in a real-world setting.
Conversely, if you focus too much on implementation, you might stop considering better coding practices, so I recommend revisiting books.
For those who already have some knowledge of JavaScript and Vue.js.
📦