In Vue.js, you can pass variables from a row as parameters to a Vue.js method and then send them out using axios

I am working on a web app that uses Django for the backend and Vue.js for the frontend. Each row in a table has a button that is intended to display detailed information about that specific row when clicked. I am trying to pass certain variables from a row in Vue.js as parameters to a Vue.js method.

However, I have encountered an issue where every time I click the button, the form gets submitted even though I have already set the type to "button".

                <tbody>
            <tr v-for="(row, index) in filteredRows" :key="`isbn-${index}`">
                <td name="`title_${index}`" v-html="highlightMatches(row.title)">{{ row.title }}</td>
                <td v-html="highlightMatches(row.author)">{{ row.author }}</td>
              
               <td><button type="button" v-on:click="greet( $event, {{ row.title }})">Greet</button></td>
                <td name="`discipline_code_course_code_${index}`"  bgcolor= "white"><div contenteditable></div></td>
                          </tr>
            </tbody>

<script>
             const app = new Vue({
        el: '#app',
        data:() => ({
            filter: '',
            rows: book_rows
        }),

        methods: {
                      greet: function (event, title) {
                alert(title);   #undefined when debug
                this.$http.post(
    '/check_code/',
    { title: title }
  );

}

        },
</script>

What is the best way to pass values from a row in Vue.js as parameters to a Vue.js method and then send them out using axios?

Answer №1

To ensure that Django does not remove certain attributes from the template before JavaScript utilizes them, make use of the verbatim tag: https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#verbatim

Enclose your JS template (currently within your HTML file served by Django) with the verbatim tag to prevent Django from interpreting the bracketed variables:

{% verbatim %}
<div>{{ app.jsVars }}</div>
{% endverbatim %}

You can verify this by checking the source code of the resulting HTML page (right-click and select view source) - your JS template variables should be visible.


Just a quick note:

The code

v-on:click="greet( $event, {{ row.title }})"
may require review, especially if the title belongs to a backend variable which is being used differently in the row above:

v-html="highlightMatches(row.title) 

If it pertains to a backend variable, remember to add quotation marks:

v-on:click="greet( $event, '{{ row.title }}')"

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

Issue with displaying current date and time dynamically (JavaScript/JQuery)

In order to create a real-time chat using websockets, I want to show the time of a message posted in this format: "% sec/min/hour/day now". After conducting some research, I came across two functions that I have modified : // Get the TimeStamp va ...

Is there a way to import a constant variable from the source file into craco.config.js?

I'm currently working on a web app using TypeScript with React, and I am utilizing craco.config.js for configuration. In my src/theme.ts file, I have defined colors that I want to import into craco.config.js in order to use them as modifyVars. Howeve ...

The onBlur attribute does not seem to be functioning properly under a specific condition

I've been attempting to customize the appearance of a search box using the onFocus and onBlur attributes, but unfortunately I haven't been able to achieve the desired outcome. Below is my HTML code: <form action="index.php" method="post" clas ...

Styling checkboxes and adding onClick functionality in JavaScript

I want to customize the appearance of my checkboxes while still maintaining an onClick function. I came across a code for styling that hides the actual checkbox and stylizes the label, but it seems to disable the JavaScript onClick function. Is there a way ...

The inefficiency of invoking Jquery on elements that do not exist for the purpose of caching

What is the impact if JQuery attempts to access elements that do not exist? Will there be any significant CPU overhead other than script loading? Does it matter if this is done for a class or an id? For optimization purposes and to minimize simultaneous c ...

Compiling Directives in AngularJS for Faster Page Loading

I'm currently experiencing performance issues in my Angular application. The root cause seems to be the excessive use of a directive on a single page. Unfortunately, I don't have the time to break down this page into multiple sections. I am seek ...

An easy way to switch animations using CSS display:none

Dealing with some missing gaps here, hoping to connect the dots and figure this out. I'm attempting to create a functionality where a div slides in and out of view each time a button is clicked. Eventually, I want multiple divs to slide out simultane ...

Confirmation of successful email delivery displayed through contact form and toast notification

I must be missing something obvious because I can't seem to get this right. Could you lend me a hand? Currently, I am developing a contact form in Vue and Vuetify using EmailJS along with a Toast (iZiToast) notification. My goal is to display the to ...

Retrieving filter arguments from a Django Queryset within the model's manager

There is a Company model that conceals certain statuses. When the user queries Company.objects.all(), any special statuses considered inappropriate will be filtered out, as shown below: class Company(models.Model): name=models.TextField() status=mod ...

The if/else statement in my JavaScript code is malfunctioning, even though the individual code blocks have been tested successfully without the if/else

I have implemented an if/else statement to check the width of a div and adjust the iframe inside accordingly. The code itself runs without any issues, but I seem to be facing a problem with the if/else statement. You can view the site at Code: Javascript ...

Successively linking promises together within a for-each iteration

How can I ensure that a foreach loop is synchronous in AngularJS var articles = arg; articles.forEach(function(data){ var promises = [fetchImg(data), fetchUser(data)]; $q.all(promises).then(function (res) { finalData.push(res[1]); ...

Filtering in AngularJS seems to only work in one direction

I am working on implementing two different ways of filtering data - one by clicking on letters and the other by typing in an input field. <body ng-controller="MainController"> <ul search-list=".letter" model="search"> <li class= ...

Looking to compare two elements within different arrays? The method outlined below is specifically designed for comparing to individual values rather than entire arrays

Is this the right approach? How can we iterate through each array to compare values? Should these data structures be modified or transformed first? Below is the data that needs to be compared. The objective is to match userID with DocumentID. const videos ...

The route is displaying the variable as 'undefined' when I attempt to access it

I had set up CRUD for two different models (venues & artists) - venues works fine, but when I try to access 'artists/index', it gives me an error saying 'Artists is not defined'. After examining the code, I believe I need to do two ...

Filter the options in the Vue Multiselect component by using the filter() method

This component and API can be found at https://github.com/vueform/multiselect Event Attributes Description @search-change query, select$ Emitted after a character is typed. I am trying to access select$.filteredOptions methods: { inputQuery( ...

Vue.js: Triggering a method upon changes within a child component

Is there a way to trigger a method in the parent component from an action on a child component? In my case, I have added a b-country-select component to the parent component and want it to activate the test method when a change occurs. The component loads ...

Disabling animation state when a different div is clicked

I've created a card set with CSS animations triggered by clicking on the cards. While I'm satisfied with the outcome, there is an issue I need help with: when I click on a card, it animates and reveals additional content. Clicking on the same car ...

What is the best way to search for specific letters in JavaScript?

Imagine having a string such as "Hello" and wanting to check it against a specific set of characters in javascript like "j", "h", "p", "q", and "y". Here is my attempt so far: var re = new RegExp("/[jgpqy]/i"); console.log(re.test("Hello")); ...

Accessing HTML partials from separate domains using AngularJS

I am looking to load html partials from Amazon S3 by uploading them and using the public URLs like this: 'use strict'; /* App Module */ var phonecatApp = angular.module('phonecatApp', [ 'ngRoute', 'phonecatAnimatio ...

Executing a JavaScript function within the HTML body and passing a variable as an argument to the function

I recently created the following HTML code: <html> <title> Upload Infected File </title> <body> <header id = "header"> <h1 align="center">Upload Malware File</h1> <p align="center"> Pleas ...