Jan*_*utz 6 javascript vue.js vue-router vue-component vuejs2
我有一个Vue组件,它使用引导网格。在子组件中,我想获取控制器中某个div的当前宽度。
这是子组件:
<template>
<div id="bg-prev" ref="prev">
<h1>{{x}}</h1>
</div>
<template>
export default {
props: ['section'],
data() {
return {
x: 0,
y: 0,
}
},
mounted() {
this.getWindowWidth();
},
methods: {
getWindowWidth() {
this.x = this.$refs.prev.clientWidth;
}
}
};
<style>
#bg-prev {
width: 100%;
}
</style>
Run Code Online (Sandbox Code Playgroud)
在此示例中,即使我检查该元素时具有清晰的宽度,该宽度也始终为0。我在这里缺少什么,已安装的挂钩是Vue生命周期中最新的挂钩?任何帮助表示赞赏;)
除了一些错别字外,代码完美运行。(缺少结束模板标签)
不需要额外的钩子。唯一的例外是如果您在其挂载方法中切换组件的渲染。然后你会使用类似的东西
const that = this
that.showDiv = true
that.$nextTick(function () {
that.getWindowWidth()
})
Run Code Online (Sandbox Code Playgroud)
您确定它的父级在安装过程中具有宽度吗?0px 的 100% 仍然是 0px。