LoginSignup
6
3

More than 3 years have passed since last update.

Vueのref属性使って要素の現在の幅を取得する

Last updated at Posted at 2020-08-19

ref属性をつかったWidthの取得の個人メモ

現在のWidthを知りたい要素にref属性を追加する


<template>
  <div class="parentWidth" ref="getParentWidth">
    .
    .
    .
  </div>
</template>

mountedプロパティ以降に記述する(DOMが描画されてからでないと取得できないため)


mounted () {
  // 要素の幅を取得するメソッド
  this.getTargetWidth()
  // ユーザーがウィンドウサイズを変更したら実行されるようにする
  window.addEventListener('resize', this.getTargetWidth)
},
methods: {
  getTargetWidth () {
    let targetWidth = this.$refs.getParentWidth.clientWidth
    console.log(targetWidth) // 要素の幅をInt型で取得する事ができる
  }
}
6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3