Vue2+webpack4 introduces less sass, this.$ref.demo.clientWidth can not get width & height?

the project project is as follows, zhoulujun/webpack4-vue2-project-template

and then find out,

mounted () {
this.$ref.demo.clientWidth;// gets the parent node width
this.$ref.demo.clientHeight;// value is 0

this.$nextTick (() = > {
this.$ref.demo.clientWidth;// gets the parent node width
this.$ref.demo.clientHeight;// value is 0
});
setTimeout (() = > {/ / you can get the correct value
this.$ref.demo.clientWidth;
this.$ref.demo.clientHeight;
})
}

if style=" indicates width and height "directly on the element, it can be obtained.

or remove lang= "less" from style | | lang= "scss"

< style >
.demo {"indicates width, height"}
< / style >

at first I thought it was webpack happyPack, then removed all happyPack, found that this is still the case, and then modified the less sass loader configuration

{
test: /. (less) $/,
use: [
"vue-style-loader",// adds styles to dom through style tags
" style-loader",
"sass-loader"
]
},

found that the width and height still could not be obtained.
ask which god to solve the doubt, thank you!


I think so.
your page structure is dynamically inserted by js. You call it in the mounted life cycle. The dom element has just been inserted into the page. At this time, you need to get the height of the page

.

[the case where css is written in the style tag] is to wait for dom rendering, while dom rendering is performed after the execution of the micro task queue (at least js inserts this), and then calculate the height of the page before you can get it.
css is written on the line, and usually dom performs virtual calculations after it is created. [you should know that usually a tag can be created without inserting the page], so you can get

when you mounted.

and why nextTick can't get it. Depending on the version of your vue [different ways of nextTick implementation] [2.5, you can get it, because the internal implementation uses macro tasks-- (setTimeout, etc.), other versions (micro tasks-promise, etc.) are not surprisingly impossible]

Menu