Last active
March 24, 2023 02:02
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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