如何反应性地使用计算属性中元素的宽度

Mig*_*ger 5 vue.js

我试图根据组件中元素的宽度设置计算属性。问题是我不知道如何以反应性的方式获取宽度。

我的元素上有一个 ref 来获取有效的宽度。但是我似乎无法让 vue 检测到宽度正在变化

我将元素设置为:

<div ref="myDiv"></div>
Run Code Online (Sandbox Code Playgroud)

我的计算属性为:

myProperty() {
  return this.$refs.myDiv.clientWidth/2;
}
Run Code Online (Sandbox Code Playgroud)

myProperty 计算正确,但不会随着 myDiv 宽度的变化而变化

itt*_*tus 3

您可以收听resize事件

  data() {
   return {
     clientWidth: 0
    }
  },

  // bind event handlers to the `handleResize` method (defined below)
  mounted: function () {
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
  },

  methods: {
    // whenever the document is resized, re-set the 'clientWidth' variable
    handleResize (event) {
      if (this.$refs.myDiv) {
        this.clientWidth = this.$refs.myDiv.clientWidth
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后你可以this.clientWidth在你想要获取clientWidth的地方使用。

  myProperty() {
    return this.clientWidth/2;
  }
Run Code Online (Sandbox Code Playgroud)