我有一个 Vue 组件,它使用引导网格。在子组件中,我想获取 Controller 中某个 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>
在此示例中,宽度将始终为 0,即使在我检查元素时该元素具有清晰的宽度。我在这里缺少什么,已安装的 Hook 是 vue 生命周期中的最新 Hook ,对吗?任何帮助表示赞赏;)
最佳答案
除了一些拼写错误外,代码运行良好。 (缺少结束模板标记)
不需要额外的钩子(Hook)。唯一的异常(exception)是,如果您在组件的安装方法中切换组件的呈现。然后你会使用像
这样的东西const that = this
that.showDiv = true
that.$nextTick(function () {
that.getWindowWidth()
})
你确定它的父级在安装期间有宽度吗? 100% 的 0px 仍然是 0px。
关于javascript - VueJS获取Div的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46345947/