【问题标题】:Vue.js - Component Height and Width not computedVue.js - 未计算组件高度和宽度
【发布时间】:2021-04-19 09:54:30
【问题描述】:

我的组件中有以下代码:

computed: {
    gridWidth()  { return (this.$el && this.$el.offsetWidth)  },
    gridHeight() { return (this.$el && this.$el.offsetHeight) },
},
mounted(){
    console.log(this.$el && this.$el.offsetWidth, this.gridWidth, this.$el && this.$el.offsetHeight, this.gridHeight)
},

控制台输出为:

1766 undefined 931 undefined

为什么计算属性未定义?

以正确的方式成为观察者吗?为什么以及如何实现?

【问题讨论】:

  • 你有没有在你的mounted中试过这个......this.$nextTick(() => { console.log(this.$el && this.$el.offsetWidth, this. $el && this.$el.offsetHeight, this.gridHeight)})

标签: vue.js computed-properties


【解决方案1】:

这基本上与reactivity in Vue 的工作原理有关。默认情况下,您的 DOM 不会持续提供更新的值。

您可以使用vm.$nextTickvm.$watch 在渲染完成后基本上附加一个观察器,或者您可以使用一个小型库来满足您的需求:

vue-resize-directive

【讨论】:

  • 谢谢。现在,我通过 resize 事件实现了这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 2017-10-21
  • 2019-05-31
  • 2015-12-16
  • 2012-12-16
  • 2011-03-28
相关资源
最近更新 更多