I am using vue in shopify and am working on a collection page. When I click on a filter, it‘s an href and it updates the url and reloads the page.
So I have a product grid
<div class="grid-wrapper">
<template v-for="(product, index) in collection.products">
<div class="product-item"></div>
</template>
</div>
And my idea was to just use the same url with fetch so the page doesn‘t reload.
I did this
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
})
This does not work because I get back the actual <template v-for…> as the new innerHTML and vue isnt taking over. How can I solve this
In shopify I converted the object like so
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')
You're approaching this in the traditional JavaScript way of manipulating the DOM directly. In Vue, we set state which can then be rendered by your template.
Instead:
data attribute to store your statemethods, write a function to fetch your data, then update the components datacreated hooktemplate render the results
v-ifv-for to iterate over, and render listsHere's a working demo
I don't have access to your API endpoint, so for demo purposes, am just using the GitHub API, to fetch and render a list of all repos in the Vue.js organization.
Here's what it looks like:
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
name: 'dbzx10299-demo',
data() {
return {
loaded: false,
response: null,
}
},
methods: {
fetchData() {
const demoEndpoint = 'https://api.github.com/orgs/vuejs/repos';
fetch(demoEndpoint)
.then(response => response.json())
.then(data => {
this.response = data;
this.loaded = true;
})
},
},
mounted() {
this.fetchData();
},
})
<script src="https://unpkg.com/vue@2.x/dist/vue.js"></script>
<div id="app">
<div class="hello">
<h2>Vue Repo List - Data fetching example</h2>
<div v-if="!loaded">Loading...</div>
<ul v-else>
<li v-for="(repo, index) in response" :key="index">
<a :href="repo.html_url" :title="repo.description" target="_blank">
{{ repo.name }}
</a>
<i>★ {{ repo.stargazers_count }}</i>
</li>
</ul>
</div>
</div>