Vue and axios join forces to send requests and showcase the outcomes

I am in the process of setting up a Vue application that will send a request to a backend and then showcase the response on the webpage. I created this example:

new Vue({
    data: {
        message: '{}'
    },
    el: '.login-app',
});

Vue.component('message-section', {
    template: '<div>Message Section</div>'
});

Vue.component('login-component', {
    template: '<div><button v-on:click="login(\'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="107d797b755076717b753e737f7f">[email protected]</a>\', \'passwd\')">Login</button></div>',
    methods: {
        login: function (username, password) {
            axios.post("http://192.168.1.10:8080/login", {username: username, password: password})
                .then(response => {this.message = response.data})
        }
    }
});

and an index like:

<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8>
    <title>Vue Test</title>
  </head>
  <body>
    <div class="login-app">
      {{ message }}
      <message-section></message-section>
      <login-component></login-component>
    </div>
    <script src="/static/testvue.bundle.js></script>
  </body>
</html>

The concept is a basic app where a username/password are submitted and a response such as "success" is displayed. However, being inexperienced with Vue and JavaScript, I am encountering difficulties. I am unsure how to display the response anywhere. The {{ message }} in there doesn't seem to function properly. It appears that only the {} from the "message" attribute is being rendered. Also, the user/pass is hardcoded... I am uncertain how to integrate it with a form field.

I can observe the data being sent to the backend, indicating that part is functional...

Furthermore, how can a Vue project be organized into multiple "modules" or similar structures?

Edit:

If I modify it so there's only one component like this:

new Vue({
    data: {
        message: '{}'
    },
    el: '.login-app',
    methods: {
        login: function (username, password) {
            axios.post("http://192.168.91.30:8080/login", {username: username, password: password})
                .then(response => {this.message = response.data})
        }
    }

})

and

<div class="login-app>
  {{ message }}
  <button v-on:click="login(\'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9df0f4f6f8ddfbfcf6f8b3fef2f0">[email protected]</a>\', \'passwd\')">Login</button>
</div>

Then nothing displays at all... Wasn't this supposed to put them inside the same container or something similar?

Answer №1

Your revised code is now operational.

console.clear()

new Vue({
  data: {
    message: '{}'
  },
  el: '#login-app',
  methods: {
    login: function(username, password) {
      axios.post("https://httpbin.org/post", {username, password})
       .then(response => this.message = response.data.json)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js"></script>

<div id="login-app">
  {{ message }}
  <button v-on:click="login('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2226242a0f292e242a612c2022">[email protected]</a>', 'passwd')">Login</button>
</div>

The functionality is demonstrated within a component in the following manner.

console.clear()

Vue.component('login-component', {
  template: `
   <div>
     <button v-on:click="login('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad7d3d1dffadcdbd1df94d9d5d7">[email protected]</a>', 'passwd')">Login</button>
   </div>`,
  methods: {
    login: function(username, password) {
      axios.post("https://httpbin.org/post", {username, password})
      .then(response => this.$emit('login-success', response.data.json))
    }
  }
});

new Vue({
  data: {
    message: '{}'
  },
  el: '#login-app',
  methods: {
    onSuccess(message) { this.message = message }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.min.js"></script>

<div id="login-app">
  {{ message }}
  <login-component @login-success="onSuccess"></login-component>
</div>

In this alternate example, please note that message acts as a data property of the parent Vue instance. The login-component does not directly have access to message. Therefore, if the ajax call is executed within the component, the value needs to be emitted from the component in order to set message. This is accomplished by emitting the custom event login-success with the success value passed as a parameter. The parent Vue instance listens for this event using the syntax below:

<login-component @login-success="onSuccess"></login-component>

Answer №2

Your component login-component is facing an issue where it does not have access to the message property, which actually belongs to the root Vue app.

An easy solution would be to simply move the message into the component itself:

Vue.component('login-component', {
  template: '<div><button v-on:click="login(\'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb0b4b6b89dbbbcb6b8f3beb2b0">[email protected]</a>\', \'passwd\')">Login</button></div>',
  data() { 
    return { message: '' }
  },
  methods: {
    login: function (username, password) {
      axios.post("http://192.168.1.10:8080/login", {username: username, password: password})
        .then(response => {this.message = response.data})
      }
    }
});

If the message should not exclusively belong to login-component, you might need to consider using Vuex or emitting custom events (this and this).

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

JavaScript and Responsive Design Techniques

I'm struggling to create a responsive page that starts with a mobile-first approach, but I keep running into the same issue. When I have my dropdown menu in the mobile version, it looks good. However, when I try to switch it to the non-mobile version ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...

Output each element of an array in Vuejs2 with a line break between each

I am currently working with vuejs2 and have a select tag where a person is selected, with their address properties directly bound to the element. I need to display the address of the selected person. I attempted to use an array in order to print out the el ...

The header() function triggers automatic page redirection instead of waiting for the form to be submitted

When I created a form that automatically sends an email upon submission, my goal was to direct the user to a thank you page after the email is sent. In my search for a solution, I stumbled upon the header() function in php and attempted to use it with the ...

What could be the reason for the incorrect parsing of this JSON data?

Issue arising due to unparseable JSON in JavaScript and jQuery API. Here is the code snippet: JSON parsing issue in JavaScript: // Code sample: alert(data); // output is an object alert(data.horas[0].hora; // returns undefined The JSON structure: {"hor ...

I can't figure out why my JavaScript recursion function isn't correctly counting the number of lines, words, and characters in a text

Seeking assistance with my JavaScript recursion program that is not functioning as expected. The goal is to extract words from a text file and output the count of words, lines, and characters. I am uncertain where my mistake lies, so any guidance on code m ...

Upgrading to Vue 3: Assigning unique keys to components within templates

In Vue 2, to place two components side by side in a template, it is necessary to set a unique key for each component. The keys should be different (for example, applying string concatenation with a prefix). https://i.sstatic.net/eKs84.png Vue 2 solution: ...

Delete the class when the user clicks anywhere on the page

I have 2 buttons that will toggle/remove a class when the user clicks on them. $('.social-toggle').on('click', function() { $('.social-networks').not($(this).next()).removeClass('open-menu') $(this).next().toggl ...

Is there a way to execute all functions with their respective arguments simultaneously using just one `run()` command?

Imagine having two separate files to work with: File 1 exports.run = () => { console.log(test.property, test2.property, etc.property) }; exports.info = { name : "test" } File 2 const fs = require('fs'); let test; let test2; ...

Execute a simulated click function in JavaScript without causing the viewport to move

I have successfully implemented a sticky add to cart feature on my Shopify store. However, there seems to be an issue where clicking on the variations in the sticky area also triggers the same variations on the product page, making it difficult for users t ...

Determine the total sum of values for various keys that share the same ID in JavaScript

I am interested in finding a way to add together the values of multiple keys for the same ID in an object using JavaScript. Specifically, I want to sum the price and total keys for each unique ID in my object. var obj = [{ id: "1", price: 100, tot ...

Trying to remove just one task, but ending up deleting all tasks instead in Vue 2 with Vuex 3

I've encountered an issue while using Vuex for my simple to-do app. When I attempt to delete a single to-do item, all of the todos are getting deleted instead. This behavior has left me puzzled as I am only deleting the one that matches the id of the ...

proper way to delete an event listener in vue 3

I have a function that listens for viewport dimensions when the project is first mounted and also after each resize event. However, I am unsure of the correct way to remove this listener. const { createApp, onMounted, ref } = Vue; const app = createA ...

Can a Singular Ajax Call be Configured for Multiple Inputs?

Within a PHP file, there is a form tag containing multiple inputs of type submit (essentially buttons) generated automatically by an external PHP script with names like button0, button1, etc. My goal is to utilize AJAX and jQuery to send the value of the c ...

The search for Javascript is futile when utilizing .Net RijndaelManaged

I have implemented an encryption/decryption process in my C# WCF using the following code: public static string EncryptString(string InputText, string Password) { RijndaelManaged RijndaelCipher = new RijndaelManaged(); RijndaelCiph ...

I want to create a feature in Angular where a specific header becomes sticky based on the user's scroll position on the

When working with Angular, I am faced with the challenge of making a panel header sticky based on the user's scroll position on the page. I have identified two potential solutions for achieving this functionality. One involves using pure CSS with pos ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

Comparison between PHP's JSON parser and Javascript's JSON parser

Can anyone help me with this PHP serialize JSON encoding issue? json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))')); // output json: {"pattern":"^(?:\/?site ...

Tips on obtaining a dynamically generated document identifier before uploading a file to Firebase storage, and implementing it as a reference for web storage

Before sending a group of writes to Firestore with an automatically generated ID, I have a function that uploads an image file to Firebase storage. The code is set up to wait for the file to be uploaded before getting the download URL and then uploading th ...

Guide to transferring a PHP variable from a loop and converting it into a JavaScript variable

I am having an issue with accessing specific row values in a while loop that displays data from a mysql table into a table. Each row has a button to send data via ajax to another PHP page for insertion into another table. However, since I am outside of the ...