javascript - VueJS获取Div的宽度

标签 javascript vue.js vuejs2 vue-component vue-router

我有一个 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/

相关文章:

javascript - LESS 在 IE11 中不起作用 - 为什么?

javascript getElementsByClassName 不适用于 <select>

vue.js - default.vue Jest 中的 <nuxt/> 组件出现未知自定义元素 : - did you register the component correctly? 错误

javascript - 如何从组件中的 vuex action 返回状态数据

node.js - 运行 npm install 时 node-sass 出错

javascript - Vuejs <keep-alive> 有什么意义?

javascript - Jquery Ajax表单没有成功消息

javascript - 获取与当前单元格相邻的第四个单元格的类

javascript - 同一页面上的相同 Vue 组件两次重复组件 View

javascript - 在 dom 中移动 Vue 组件?