javascript VueJS 获取 Div 的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46345947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:37:03  来源:igfitidea点击:

VueJS get Width of Div

javascriptvue.jsvuejs2vue-componentvue-router

提问by Jan Schmutz

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.

我有一个使用引导网格的 Vue 组件。在子组件中,我想获取控制器中某个 div 的当前宽度。

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 ;)

在此示例中,宽度将始终为 0,即使我检查元素时该元素具有清晰的宽度。我在这里错过了什么,挂载的钩子是 vue 生命周期中最新的钩子,对吗?任何帮助表示赞赏;)

采纳答案by user1497119

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.

您确定它的父级在安装过程中具有宽度吗?0px 的 100% 仍然是 0px。