BuzzFuzz
BuzzFuzz

Reputation: 165

How to Pass Vue data into Axios Post Request?

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

Upvotes: 0

Views: 1923

Answers (1)

S&#248;lve
S&#248;lve

Reputation: 4406

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
}

Upvotes: 2

Related Questions