Home » vue » How to Pass Vue data into Axios Post Request?

How to Pass Vue data into Axios Post Request?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am trying to pass some Vue data to axios.post Request but passing it using Vue template doesn’t work. How would I go about passing the Data?

My Code:

<body>
    <div id="app" class="container">
        <div>
            <input type="text" name="username" placeholder="Username" v-model="loginForm.username">
            <input type="password" name="password" placeholder="Password" v-model="loginForm.password">
            <input type="submit" value="Login" v-on:click.prevent="loginUser()">
        </div>

    <script>
        var app = new Vue({
            el: "#app",
            delimiters: ['[[', ']]'],
            data: {
                loginForm: {
                    username: "",
                    password: ""
                },
            },
            methods: {
                loginUser() {
                    axios.post('/rest-auth/login/', {
                            // Using delimeters so [[ foo ]] but still doent work
                            username: [[ loginForm.username ]],
                            password: [[ loginForm.password ]],
                        })
                        .then(function (response) {
                            console.log(response);
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                }
            }
        })
    </script>
</body>

FYI [[ loginForm.username ]] and [[ loginForm.password ]] renders fine in HTML (as text).

Answers:

You are comfusing delmitters in JS with HTML.

To access data properties in vue, you have to do it as following:

this.loginForm.username

The this variable is the vue component instance. You can veryfi this by trying to console log this inside your function. this stores all things declared in your component. Computed properties, data properties, functions(methods) etc…

So in your case, you would sit the value of the key username like so:

{
  username: this.loginForm.username,
  password: this.loginForm.password
}