The Vue application successfully retrieves data from the API, however, the objects are not being properly rendered onto my template resulting in the text not appearing as

I have successfully developed a Vue application that retrieves data from my Django REST API and displays it on a webpage. The data comprises a list of objects structured as {'name': Whitney Portal, 'parent': Inyo National Forest', 'camp_id': 232123}

Within the app, there is an input field where users can type text, and the Vue app will dynamically show all objects containing the input text.

Although the app seems to be loading objects into the template, none of the desired text is visible. My goal is to showcase the camp attributes, such as the name, for each object.

To track the number of displayed objects at any given time, I appended a random string 'I'm HERE!' in the HTML to each generated object. However, only this text is being shown for each object.

Upon typing in the input field, the count of objects (and occurrences of 'I'm HERE!') changes accordingly. The objects respond as expected (I know what text to input to display only one object). For instance, entering 'Inyo' results in displaying only one object since only one object in the database has 'Inyo National Forest' as a parent attribute.

When nothing is typed, the number of displayed objects aligns with the database count. Inspecting the developer tools > Network reveals a successful API GET request was executed, and the response contains all the data.

No errors are reported in the console. Has anyone else faced this issue before and found a solution?

I am utilizing Django, Django REST Framework, and Vue JS

Vue app

const App = new Vue({
    el: '#show-camps',
    data() {
        return {
            campgrounds: [],
            search: '',
            test: 'test',
        };
    },
    async created() {
        const response = await fetch('http://localhost:8000/api/campgrounds/');
        this.campgrounds = await response.json();
    },
    methods: {
    },
    computed: {
        filteredCamps: function(){
            return this.campgrounds.filter((camp) => {
                return camp.parent.match(this.search);
            });
        }
    }
})

My template

<!DOCTYPE html>
{% extends 'base/base.html' %}
{% load static %}
{% block title %}Campground List{% endblock %}
{% block content %}
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="head col-12 col-sm-10 col-md-7 text-center solid">
            <h1>List of all campgrounds</h1>
            <p>Here is a list of some campground IDs that I've collected.</p>
            <hr>
        </div>
    </div >

    <!--Campground ID Display-->
    <div class="row justify-content-center">
        <div class=" col-12 col-sm-10 col-md-7 text-center solid">
            <div id="show-camps">
                <input type="text" v-model="search" placeholder="search campgrounds"/>
                <div v-for="camp in filteredCamps">
                    <div>
                        {{camp.name}}
                        {{camp.camp_id}}
                        {{camp.parent}}
                        {{ test }}
                    </div>
                    I'm HERE!
                    {{camp.name}}
                    {{camp.camp_id}}
                    {{camp.parent}}
                    {{ test }}
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
    <script type="text/javascript" src="{% static 'js/vue.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/main.js' %}"></script>
{% endblock %}

API Response

[
    {
        "camp_id": "232122",
        "name": "WHITE BRIDGE",
        "parent": "Dixie National Forest"
    },
    {
        "camp_id": "232123",
        "name": "WHITNEY PORTAL",
        "parent": "Inyo National Forest"
    }
]

Answer №1

The issue here is that Vue and Django both utilize the same mustache template syntax for displaying variables, causing conflict as they try to display server-side variables within your code.

To resolve this conflict effectively, you can instruct Django not to interpret tags by using the verbatim tag:

{% verbatim %}
<div id="show-camps">
  <!-- insert your Vue template code here -->
</div>
{% endverbatim %}

Alternatively, another approach is to adjust Vue settings using the delimiters option. For instance:

const App = new Vue({
  el: '#show-camps',
  delimiters: ["[[", "]]"],
  // additional configurations
})

You can then modify your HTML template accordingly:

<div>
  [[ camp.name ]]
  [[ camp.camp_id ]]
  [[ camp.parent ]]
</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

Unable to bring in the Firebase Firestore Colletion

When working on my next app, I encountered an error while trying to call a Firestore Collection. The specific error message that appeared when I ran the app was: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicat ...

Positives and negatives images for accordion menu

I have successfully created an accordion list using HTML, CSS, and JavaScript. However, I would like to enhance it by adding a plus and minus picture in the left corner of the heading. Is there a way to achieve this functionality? I have two images that I ...

PHP script not being triggered by Ajax upload

After identifying and fixing errors through the Chrome console log, I am facing a new issue where the PHP script responsible for processing the data is not being called. <legend><strong>Choose a machine model</strong></legend> < ...

A guide on integrating Django's {% trans %} tag with Pug/Jade for seamless translation functionality

I've integrated pypugjs into my Django project, which bears a striking resemblance to pyjade. Here's a snippet from my .pug file: H3 Bottle Form form(method="post" action=".") | {% csrf_token %} | {{ form.as_p }} input(type="submit" ...

Exploring the capabilities of setState within conditional statements in React Native

Hello there! Currently, I am attempting to export exportTest to a separate js file in order to re-render. Here is my approach: import React, { useState } from 'react'; import { StyleSheet, View } from 'react-native'; var n; export var ...

Using Angular to fetch API response and convert it into a promise

I've been following the Angular tutorial available at https://angular.io/tutorial/toh-pt6. The tutorial demonstrates how to retrieve a Json response from an API call and then match it to a promise. One specific example from the tutorial is as follows ...

What is the best way to change the date format in the GET API response for all objects

Recently started working with Angular, I'm receiving object data from an API call. data= [ { "Id": 4, "IssueDate": "2021-01-25T15:17:00.85", "ExpiryDate": "2021-01-25T15:25:40.263" ...

Interacting between frames with jQuery

I have main_page.htm with the following frameset structure: <frameset rows="30,*" frameborder=0 border=0> <frame name="top_frame" src="top.htm"> <frame name="bottom_frame" src="bottom.htm"> </frameset> The content in ...

Having difficulty accessing and modifying child elements

I am encountering an issue where the 'remove' property is showing as undefined when I try to add or remove a class on an element. Upon inspecting the parent element using element.parentNode, I can see that there are child span elements present. H ...

Learn how to iterate over an array and display items with a specific class when clicked using jQuery

I have an array with values that I want to display one by one on the screen when the background div is clicked. However, I also want each element to fade out when clicked and then a new element to appear. Currently, the elements are being produced but th ...

Having trouble getting the Django image to show up on the website

I'm facing an issue with displaying image files that are stored in the database. When I directly input the filename, the image appears without any problems. However, when using the current code, it shows a broken image. The other variables not related ...

Issue encountered when attempting to set a default value in Material-UI Text Field while interacting with Redux state?

Struggling to assign a defaultValue property for a Text Field using data from Redux state, but the updates are not reflecting as expected. The value is passed down as a prop from the container component to the edit component like this: render() { const ...

Attempting to retrieve certain information, however encountering the error message "Cannot read property '0' of undefined at XMLHttpRequest.xhr.onreadystatechange"

Essentially, I am attempting to retrieve a specific set of data from an API showcasing only the names of the football home teams and then displaying them in a table format. However, despite being able to fetch the entire dataset from the API successfully, ...

JavaScript Refresh Function Malfunctioning

Currently, I have a JavaScript code snippet on my website that automatically refreshes an iframe every three seconds. window.setInterval(function() { reloadIFrame() }, 3000); function reloadIFrame() { var frame = document.getElementById("if ...

Converting Plain JSON Objects into a Hierarchical Folder Structure using Logic

Looking at the data provided below: [ {name: 'SubFolder1', parent: 'Folder1'}, {name: 'SubFolder2', parent: 'SubFolder1'}, {name: 'SubFolder3', parent: 'SubFolder2'}, {name: 'Document ...

Using the novalidate attribute in Angular 4.0.0

Since migrating to angular 4, I have encountered a peculiar issue with my template-driven form. The required attribute on the input field appears to be malfunctioning. It seems like the form has the novalidate attribute by default, preventing HTML5 validat ...

Using javascript code to encode images to base64 and save the output to a text file

How can I modify the code below: <p id="demo"></p> <script> var openFile = function(event) { var input = event.target; var reader = new FileReader(); reader.onload = function(){ var dataURL = read ...

Efficient Management of Passed Variables in res.render() Using Node.js and Express

One of the routes in my app renders an HTML file using EJS, passing a variable along with it. myFunc(username).then(user=>{ res.render('normalHTML.ejs') }).catch(err => { res.render('error.ejs', {overwrite: er ...

Problem Encountered with element.html() Method in Angular Directive

Recently, I started working with Angular and came across an issue with a directive. In the linkFunction, I used attributes["attribute-value"] to set the scope to a specific value. To my surprise, when trying to access element.html(), I didn't get the ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...