Issue with Vue not displaying HTML content retrieved from an API

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')

Answer №1

Instead of directly manipulating the DOM in the traditional JavaScript way, Vue allows you to set state which can then be rendered by your template.

Here are the steps:

  1. Create a data attribute to store your state
  2. Write a function under methods to fetch your data and update the components data
  3. Call your function in the component's created hook
  4. In your template, render the results
    • Make sure to use v-if to check if it's present first
    • You can utilize v-for to iterate over and render lists

Check out this working demo


For demonstration purposes, I am using the GitHub API to fetch and display a list of all repos in the Vue.js organization since I don't have access to your API endpoint.

This is how it appears:

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fffcecc9bba7f1">[email protected]</a>/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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with JWT authentication causing SockJS handshake to block WebSocket connection attempts

I have an operational Spring Boot server with Authentication/Authorization features. However, I am facing issues when trying to establish a connection with SockJS due to my security protocols blocking it. Although I do not have a complete understanding of ...

Deactivate the button with jquery after it has been clicked

I am currently developing a project on opencart. I have a specific requirement where I need to restrict users from purchasing multiple products, allowing them to only buy one product per customer ID. To achieve this, I need the add to cart button to automa ...

Rotation Ensuring a Seamless Transition to a Specific Angle

I'm currently trying to figure out how to rotate an object at a speed of 160 degrees per second, gradually slowing down until it comes to a stop at a specific angle. For instance, if the target angle is set to 30 degrees, the object should spin quickl ...

What is the basic structure of a JSON-like object?

How can data be effectively stored in a JSON-like structure? I have noticed two different approaches to storing data within a json object, each with its own method for accessing the data (illustrated using examples in Python): Approach 1: obj1 = [ {" ...

The functionality of react-waypoint's onEnter/onLeave event handlers seems to be malfunctioning

Recently, I experimented with react-waypoint to control the visibility of a div. The code works as intended by hiding the div when it reaches the waypoint inside onEnter. When the div is inside, the isInView state becomes true, which in turn triggers the d ...

Running Protractor tests can be frustratingly sluggish and frequently result in timeouts

After spending most of the afternoon struggling with this test, I've tried different approaches but none seem to work. The task at hand is searching for users within the company, generating a table, and selecting the user that matches the name. Curren ...

How to dynamically insert elements into the HTML page using Angular

When my page first loads, it looks like this <body> <div class="col-md-12" id="dataPanes"> <div class="row dataPane"> Chunk of html elements </div> </div> <div class"col-md-12 text-right"> <input type="butt ...

How to change the background color of a slider using jQuery

As a newcomer to web programming, I am currently working on incorporating a slider into my website using jQuery. My goal is to change the background color of the slider to red when the value is less than 5 and green when it exceeds 5. Can this be achieved ...

Show the image using material-ui-dropzone

Currently, I am engaged in a ReactJS project where I have implemented material-ui-dropzone to upload and exhibit an image. The uploading part has been successfully completed. However, my current obstacle lies in figuring out how to display this uploaded im ...

Accessing the JSON file from the Google Maps Places API using either JavaScript or PHP

In the midst of developing an application, I am working on fetching a list of places near a specific latitude and longitude. After obtaining an API key, inputting it into the browser URL successfully retrieves a JSON file containing the desired places dat ...

Contrasting include versus block in Jade

Can you explain the distinction between blocks and include in Jade template creation? How do you determine when to use each one? ...

Leveraging $http and $q in an Angular configuration with a service/provider

My goal is to load specific configurations for each controller in the app.config section. Each controller requires a distinct set of data, but these sets are not mutually exclusive. I am struggling to find a solution to this issue. .config(['$routePr ...

Steps for implementing remote modals in Bootstrap 5 using CS HTML

I'm attempting to implement a remote modal window in Bootstrap 5 with C# MVC. The endpoint for the modal partial view is configured correctly. According to this discussion on Github, all that needs to be done is to call some JavaScript. However, it ...

Issue with running the Jquery each function within a textbox inside an ASP.NET gridview

Below is the gridview markup: <asp:GridView ID="gvDoctorVisits" runat="server" DataKeyNames="AdmissionId" class="tableStyle" AutoGenerateColumns="False" Width="100%" EmptyDataText=& ...

Retrieve libraries from package-lock.json file

I am tasked with extracting all the libraries and versions from the package-lock.json file. Let me provide some context. I am implementing a security module within Jenkins to create an inventory of libraries used in each application. The goal is to gather ...

Utilizing React Native to Query, Filter, and Save a Single Document Field Value from Firestore Database into a Variable/Constant

My current task involves setting up a Firebase Firestore Database in order to filter it based on a specific field value within a document. The collection I am working with is named "PRD" and consists of thousands of documents, each sharing the same set of ...

Storing checkbox values in a MySQL database using PHP

I am working on a project that involves two checkbox filters. My goal is to keep track of the count of checked checkboxes for each filter and store this information in separate columns in a MySQL table. Could someone please assist me in obtaining the coun ...

Concealing a section of a table with JavaScript while preserving the original table structure

I made some adjustments to the script tag: $(document).ready(function) { Now, the evenTd's are hidden correctly. Here is the table with the code provided: <table> <tr> <td>itemOne</td> <td class="even ...

jQuery.post() function encounters issues with data not being properly posted

I am currently tackling a project that involves sending JSON data to a specific URL. I've been attempting to utilize the jQuery.post() method for this task, but I've run into a couple of roadblocks. The initial issue I'm facing is: jQuery. ...

Using jQuery's .grep() method on an array will only return the final digit

Could someone help me understand the behavior of jQuery's .grep() method? I'm creating a jQuery object array based on the names of these elements: <div class="small1 other">S1</div> <div class="small2">S2</div> <div c ...