VueJS 获取 Div 的宽度
VueJS get Width of Div
我有一个 Vue 组件,它使用 bootstrap 网格。在子组件中,我想获取控制器中某个 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,即使在我检查元素时该元素具有明确的宽度。我在这里缺少什么,已安装的挂钩是 vue 生命周期中的最新挂钩,对吗?感谢任何帮助 ;)
除了一些拼写错误外,代码运行良好。 (缺少结束模板标记)
不需要额外的钩子。唯一的例外是,如果您在组件的安装方法中切换组件的呈现。然后你会使用像
这样的东西
const that = this
that.showDiv = true
that.$nextTick(function () {
that.getWindowWidth()
})
你确定它的父级在安装期间有宽度吗? 0px 的 100% 仍然是 0px。
我有一个 Vue 组件,它使用 bootstrap 网格。在子组件中,我想获取控制器中某个 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,即使在我检查元素时该元素具有明确的宽度。我在这里缺少什么,已安装的挂钩是 vue 生命周期中的最新挂钩,对吗?感谢任何帮助 ;)
除了一些拼写错误外,代码运行良好。 (缺少结束模板标记)
不需要额外的钩子。唯一的例外是,如果您在组件的安装方法中切换组件的呈现。然后你会使用像
这样的东西const that = this
that.showDiv = true
that.$nextTick(function () {
that.getWindowWidth()
})
你确定它的父级在安装期间有宽度吗? 0px 的 100% 仍然是 0px。