赞
踩
要监听元素高度变化,你可以使用 Vue.js 的 $watch 方法。
首先,在你的 Vue 组件的 data 中声明一个变量来存储元素的高度:
- data() {
- return {
- elementHeight: 0
- }
- }
然后,在 mounted 钩子函数中使用 $watch 方法监听 elementHeight 变量:
- mounted() {
- this.$watch('elementHeight', newHeight => {
- // 当 elementHeight 变化时,这里的代码将会执行
- console.log(`元素的新高度是:${newHeight}`)
- })
- }
在你的模板中,你可以使用元素的 offsetHeight 属性来获取它的高度:
- <template>
- <div ref="element" @click="updateHeight">点我更新高度</div>
- </template>
-
- <script>
- export default {
- methods: {
- updateHeight() {
- this.elementHeight = this.$refs.element.offsetHeight
- }
- }
- }
- </script>
现在,当你点击这个元素时,你就可以在控制台看到元素的新高度了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。