LoginSignup
1
1

More than 3 years have passed since last update.

Nuxt.jsでpictureタグのコンポーネントを作る

Last updated at Posted at 2020-10-16

手順1

http://scottjehl.github.io/picturefill/
ここでjsをダウンロードして、static/assets/js/picturefill.min.jsに配置

手順2

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

nuxt.config.js
export default {
  head: {
    script: [{ src: '/assets/js/picturefill.min.js', async: true }]
  }
}

手順3

イメージコンポーネントの作成

components/atoms/photo.vue
<template lang="pug">
.a-photo
  template(v-if="res")
    picture.a-photo-picture
      source(v-bind="bindSource")
      img.a-photo-img(v-bind="bindImg")
  template(v-else)
    img.a-photo-img(v-bind="bindImg")
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true
    },
    alt: {
      type: String,
      required: false,
      default: ''
    },
    ext: {
      type: String,
      required: false,
      default: 'png'
    },
    res: {
      type: Boolean,
      required: false,
      default: false
    },
    static: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  computed: {
    breakPoint: () => 768,
    bindSource() {
      return {
        srcset: this.static
          ? `/assets/image${this.srcset('pc')}`
          : require(`~/assets/image${this.srcset('pc')}`),
        media: `(min-width: ${this.breakPoint}px)`
      }
    },
    bindImg() {
      return {
        srcset: this.static
          ? `/assets/image${this.srcset('sp')}`
          : require(`~/assets/image${this.srcset('sp')}`),
        alt: this.alt
      }
    }
  },
  methods: {
    srcset(type) {
      return `${this.src}${this.res ? '_' + type : ''}.${this.ext}`
    }
  }
}
</script>

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

.a-photo-picture
  display block

.a-photo-img
  width 100%
  height auto
</style>

Nuxt.jsのそのほか

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