VueJS 获取 Div 的宽度 [英] VueJS get Width of Div
问题描述
我有一个使用引导网格的 Vue 组件.在子组件中,我想获取控制器中某个 div 的当前宽度.
这里是子组件:
<div id="bg-prev" ref="prev"><h1>{{x}}</h1>
<模板>导出默认{道具:['部分'],数据() {返回 {x: 0,y: 0,}},安装(){this.getWindowWidth();},方法: {获取窗口宽度(){this.x = this.$refs.prev.clientWidth;}}};<风格>#bg-prev {宽度:100%;}</风格>
在这个例子中,宽度将始终为 0,即使我检查元素时元素具有清晰的宽度.我在这里错过了什么,挂载的钩子是 vue 生命周期中最新的钩子,对吗?任何帮助表示赞赏;)
除了一些错别字外,代码运行良好.(缺少结束模板标签)
不需要额外的钩子.唯一的例外是如果您在其挂载方法中切换组件的渲染.然后你会使用类似
const that = thisthat.showDiv = 真那.$nextTick(function () {那.getWindowWidth()})
您确定它的父级在安装过程中具有宽度吗?0px 的 100% 仍然是 0px.
I have a Vue Component, that uses the bootstrap grid. In the child component I would like to get the current width of a certain div in the controller.
heres the child component:
<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>
In this example the width will always be 0, even though the element has a clear width when I inspect it. What am I missing here, the mounted hook is the latest one in the vue lifecycle right? Any Help is appreciated ;)
Apart from a few typos the code is perfectly working. (missing closing template tag)
There is no additional hook needed. Only exception would be if you toggle the rendering of the Component in it's mounted method. Then you would use something like
const that = this
that.showDiv = true
that.$nextTick(function () {
that.getWindowWidth()
})
Are you sure it's parent is having a width during mounted? 100% of 0px is still 0px.
这篇关于VueJS 获取 Div 的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!