I am currently utilizing Vue in a Shopify environment and focusing on enhancing a collection page. The issue I encountered is that when clicking on a filter, it acts as an href which updates the URL and triggers a page reload.
My objective is to display a product grid
<div class="grid-wrapper">
<template v-for="(product, index) in collection.products">
<div class="product-item"></div>
</template>
</div>
I came up with the idea of maintaining the same URL while using fetch so that the page does not reload.
This was my approach
fetch('/collections?variant=black')
.then(res => res.text())
.then(html => new DOMParser().parseFromText(html, 'text, html'))
.then(data => {
document.querySelector('.grid-wrapper').innerHTML = data.querySelector('.grid-wrapper').innerHTML
})
However, this solution failed as the new innerHTML contained the actual <template v-for…>
, preventing Vue from taking control. How can I resolve this issue?
To address this in Shopify, I modified the object in the following manner
const collection = (() => {
const collection = {{ collection | json }}
const products = {{ collection.products | json }}
collection.products = products
return collection
})();
Then, in my Vue instance
new Vue.createApp({
data() {
collection: collection
}
}).mount('#app')