javascript - Vue - setting width of an element equal to the width of another element - Stack Overflow

I'm trying to dynamically set the width of my innermost element equal to the width of the outermos

I'm trying to dynamically set the width of my innermost element equal to the width of the outermost element using Vue:

<div id="banner-container" class="row">
    <div class="col-xs-12">
        <div class="card mb-2">
            <div class="banner banner-tag card-body" :style="getBannerStyle"></div>
        </div>
    </div>
</div>

I have the following code in Javascript and puted property in Vue:

var container = document.getElementById('banner-container').offsetWidth;
...
puted: {
    getBannerStyle () {
        return 'width: ' + container + 'px;';
    }
}

I'm trying to dynamically set the width of my innermost element equal to the width of the outermost element using Vue:

<div id="banner-container" class="row">
    <div class="col-xs-12">
        <div class="card mb-2">
            <div class="banner banner-tag card-body" :style="getBannerStyle"></div>
        </div>
    </div>
</div>

I have the following code in Javascript and puted property in Vue:

var container = document.getElementById('banner-container').offsetWidth;
...
puted: {
    getBannerStyle () {
        return 'width: ' + container + 'px;';
    }
}
Share Improve this question edited Jan 23, 2018 at 7:07 Bargain23 asked Jan 23, 2018 at 7:00 Bargain23Bargain23 1,9834 gold badges32 silver badges58 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

getBannerStyle is not going to be reactive because you do not access any other reactive properties within it. You need to assign a data property the offsetWidth value and reference that within getBannerStyle. Something like this should work:

mounted () {
  this.offsetWidth = document.getElementById('banner-container').offsetWidth
},
data () {
  return {
    offsetWidth: 0,
  }
},
puted: {
    getBannerStyle () {
        return `width: ${this.offsetWidth}px;`
    }
}

Unfortunately, it is next to impossible to do this in pure Vue because the element may not yet have a size during any of the lifecycle hooks. Especially, if the element is not immediately visible on page load. Fortunately, all modern browser have a class that can help: ResizeObserver.

  data: () => ({
    offsetWidth: 0,
    resizeObserver: null
  }),
  mounted() {
    this.resizeObserver = new ResizeObserver(this.onResize)
    this.resizeObserver.observe(document.getElementById('banner-container'))
    this.onResize()
  },
  beforeUnmount() {
    this.resizeObserver.unobserve(document.getElementById('banner-container'))
  },
  methods() {
    onResize() {
      this.offsetWidth = document.getElementById('banner-container').offsetWidth
    }
  }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744239761a4564647.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信