0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.jsでobject-fitしたvideoコンポーネントを作る

Last updated at Posted at 2020-12-11

手順1

https://github.com/constancecchen/object-fit-polyfill/blob/master/dist/objectFitPolyfill.min.js
ここでjsをダウンロードして、static/assets/js/object-fit-polyfill.min.jsに配置

手順2

nuxt.config.jsでjsファイルを読み込ませる

nuxt.config.js
export default {
  head: {
    script: [
      { src: '/assets/js/object-fit-polyfill.min.js', body: true }
    ]
  }
}

手順3

ビデオコンポーネントの作成

components/atoms/video.vue
<template lang="pug">
.a-video(:class="{'is-cover': cover}")
  video.a-video-movie(v-bind="bindMovie")
</template>

<script>
export default {
  props: {
    src: { type: String, required: true },
    poster: { type: String, required: false, default: '' },
    autoplay: { type: Boolean, required: false, default: false },
    loop: { type: Boolean, required: false, default: false },
    playsinline: { type: Boolean, required: false, default: false },
    muted: { type: Boolean, required: false, default: false },
    ext: { type: String, required: false, default: 'mp4' },
    res: { type: Boolean, required: false, default: false },
    cover: { type: Boolean, required: false, default: false }
  },
  computed: {
    bindMovie() {
      return {
        src: this.srcset(),
        poster: this.poster,
        autoplay: this.autoplay,
        loop: this.loop,
        playsinline: this.playsinline,
        muted: this.muted,
        type: 'video/mp4',
        'data-object-fit': this.cover ? 'cover' : false
      }
    }
  },
  methods: {
    srcset() {
      const res = this.$store.getters.innerWidth < 768 ? '_sp' : '_pc'
      return `${this.src}${this.res ? res : ''}.${this.ext}`
    }
  }
}
</script>

<style lang="stylus" scoped>
.a-video
  line-height 0

  &.is-cover
    position relative
    overflow hidden
    width 100%
    height 100%

    .a-video-movie
      position absolute
      width 100%
      height 100%
      top 0
      left 0
      object-fit cover
</style>

あと、初期化時やリサイズ時、良きタイミングでこれ使う

objectFitPolyfill()
mounted() {
  objectFitPolyfill()
  window.addEventListener('resize', objectFitPolyfill())
}

参照

Nuxt.jsのそのほか

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?