Giter Club home page Giter Club logo

gridsome-source-shopify's Introduction

gridsome-source-shopify

Shopify source plugin for Gridsome

This plugin supports the Storefront API's transformedSrc image field, as well as currency formatting.

  1. Install
  2. Usage
  3. Routes & Templates
  4. Page Query
  5. Metafields
  6. Additional Resolvers
  7. Helpful Snippets

Install

yarn:

yarn add gridsome-source-shopify

npm:

npm install gridsome-source-shopify

Usage

gridsome.config.js

module.exports = {
  plugins: [
    {
      use: 'gridsome-source-shopify',
      options: {
        storeName: '<my-store>', // OR
        storeUrl: 'https://<my-store>.myshopify.com',
        storefrontToken: '<storefront-api-token>', //Required
        typeName: 'Shopify', // Optional, default is 'Shopify'
        types: [ 'Product', 'Collection' ], // Optional, default is all types
        perPage: 100 // Optional, default is 100
      }
    }
  ]
}

Routes & Templates

Now you can create a template called ShopifyProduct.vue, and specify the route for it - Gridsome will automatically generate pages for all products.

gridsome.config.js

module.exports = {
  templates: {
      ShopifyProduct: '/product/:handle'
  }
}

You can also specify templates to use if you do not want to name the template files Shopify<type>, or if you want to change the page routes:

gridsome.config.js

module.exports = {
  templates: {
      ShopifyProduct: [
        {
          path: '/product/:handle',
          component: './src/templates/Product.vue'
        }
      ],
      ShopifyCollection: [
        {
          path: '/collection/:handle',
          component: './src/templates/Collection.vue'
        }
      ]
    },
  }

Page Query

Once you have specified the route for a type, you can query it by ID.

<page-query>
query Product ($id: ID!) {
  shopifyProduct (id: $id) {
    id
    descriptionHtml
    title
  }
}
</page-query>

Now this product will be available at this.$page.shopifyProduct:

<template>
  <Layout>
    <h1>{{ $page.shopifyProduct.title }}</h1>
    <div v-html="$page.shopifyProduct.descriptionHtml" />
  </Layout>
</template>

Metafields

To make metafields available to query in the Storefront API, you should follow this guide: Retrieve metafields with the Storefront API. Then metafields will be available in your product query.

Additional Resolvers

This plugin adds a couple of custom resolvers to help with image sizing, and currency formatting.

transformSrc

Each image type includes a transformSrc field, similar to the Shopify Storefront's. You can create different image sizes and scales with this - for example, creating a thumbnail image, and a card/cover image:

...
  image {
    ...
    thumbnail: transformedSrc(maxWidth: 100, maxHeight: 100, crop: CENTER)
    coverImage: transformedSrc(maxWidth: 600, maxHeight: 400, crop: CENTER)
  }
...

amount

Each price type includes extra formatting arguments in the amount field, where you can specify if you want to, and how to, format the price asa currency:

...
  price {
    amount(format: true) # Defaults to en-US locale, and the store's currency code.
    # Result: $25.00
  }
...
...
  priceRange {
    minVariantPrice {
      amount(locale: "en-GB", currency: "GBP") # Specify a locale and a currency code to use.
      # Result: £25.00
    }
  }
...

Helpful Snippets

You will probably need to find a product variant by the options that have been selected - computed properties are your friend...

<template>
  ...
    <div
      v-for="option in $page.shopifyProduct.options"
      :key="option.id"
      class="field">
      <div class="control">
        <label
          :for="option.name"
          class="label">
          {{ option.name }}
          <div class="select is-fullwidth">
            <select
              :id="option.name"
              v-model="selectedOptions[option.name]">
              <option
                v-for="value in option.values"
                :key="value"
                :value="value">
                {{ value }}
              </option>
            </select>
          </div>
        </label>
      </div>
    </div>
    <div>
      <img :src="currentVariant.image.transformedSrc">
      <div v-html="$page.shopifyProduct.descriptionHtml" />
    </div>
  ...
</template>

<script>
export default {
  data: () => ({
    selectedOptions: {}
  }),
  computed: {
    currentVariant () {
      // Find a variant where every variants options matches those that are currently selected
      return this.$page.shopifyProduct.variants.find(variant => variant.selectedOptions.every(({ name, value }) => value === this.selectedOptions[ name ]))
    }
  },
  // Set the first variant as a default option
  mounted () {
    const [firstVariant] = this.$page.shopifyProduct.variants
    this.selectedOptions = firstVariant.selectedOptions.reduce((options, { name, value }) => ({ [ name ]: value, ...options }), {})
  },
  // The mounted hook doesn't always run on page change - so make sure we set the first variant if the route changes
  watch: {
    $route (to, from) {
      const [firstVariant] = this.$page.shopifyProduct.variants
      this.selectedOptions = firstVariant.selectedOptions.reduce((options, { name, value }) => ({ [ name ]: value, ...options }), {})
    }
  }
}
</script>

All Shopify products have at least one variant - even if a product has no options (i.e. colour/size), it will have a default variant that contains the base product price/title etc. This single variant will also create a default option (title), which you will most likely want to filter out, as there is only one variant you can select anyway. If this is the case then the product options should be hidden, and the single variant set as the default selected option (as above):

<template>
  ...
    <div
      v-for="option in productOptions"
      :key="option.id"
      class="field">
      ...
    </div>
  ...
</template>

<script>
export default {
  ...
  computed: {
    // Single variants have an default option called 'Title' - filter this out.
    productOptions () { return this.product.options.filter(({ name }) => name !== 'Title') },
  }
  ...
}
</script>

You can also create relationships from products/product variants to other types, if they return an ID or array of ID's as one of their fields. For example, with Contentful's integration you could do something like the below:

gridsome.server.js

module.exports = api => {
  api.loadSource(actions => {
    const contentfulProducts = actions.getCollection('ContentfulProduct')
    contentfulProducts.addReference('shopifyProductVariantId', 'ShopifyProductVariant')
  }
}

Then query the actual product/product variant from within a query:

query {
  allContentfulProduct {
    edges {
      node {
       name
        shopifyProductVariantId {
          id
          title
          price {
            amount
          }
        }
      }
    }
  }
}

gridsome-source-shopify's People

Contributors

travis-r6s avatar renovate[bot] avatar renovate-bot avatar dependabot[bot] avatar cameronrr avatar rylanharper avatar terabytetiger avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.