Skip to content

Instantly share code, notes, and snippets.

@rylanharper
Last active March 24, 2023 02:02
Show Gist options
  • Select an option

  • Save rylanharper/5b0f02e8ca9c0c4dc46f7006b2ee211e to your computer and use it in GitHub Desktop.

Select an option

Save rylanharper/5b0f02e8ca9c0c4dc46f7006b2ee211e to your computer and use it in GitHub Desktop.
Shopify Metafield Product Reference List With Vue(2) or Vue(3) | 2023-01 API Version
export default {
name: 'ProductReference',
props: {
product: {
type: Object,
required: true
}
},
data() {
return {
swatchProducts: [],
}
},
created() {
this.fetchSwatchProducts()
},
methods: {
// `fetchSwatchProducts` is a handy function if you add in a custom metafield product reference type (for swatches or variations):
// swatches: metafields(identifiers: { namespace: "custom", key: "product_swatches" }){
// key
// value
// namespace
// }
async fetchSwatchProducts() {
const swatches = this.product.swatches[0]?.value
? JSON.parse(this.product.swatches[0].value)
: []
if (swatches.length === 0) {
return
}
const productIds = swatches.map(swatch => `${swatch}`)
const query = `query GetProductsByIds($ids: [ID!]!) {
nodes(ids: $ids) {
... on Product {
id
title
handle
images(first: 1) {
edges {
node {
id
altText
height
width
url
}
}
}
}
}
}`
// I am using graphql-request here, but apollo will work
const data = await this.$graphql.request(query, { ids: productIds })
this.swatchProducts = data.nodes.filter(node => node !== null)
}
// Now you can use in template like this and get all the reference product's data:
// <div v-if="swatchProducts.length">
// <h3>Swatch Products:</h3>
// <div v-for="swatchProduct in swatchProducts" :key="swatchProduct.id">
// <span>{{ swatchProduct.title }}</span>
// </div>
// </div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment