Dude4
Dude4

Reputation: 163

Vue: every object in data is undefined

Code ->

<div>    
    <h2>Login</h2>    
      <div class="submit-form">
        <div class="form-group">
    <label for="email">Title</label>
    <input
      type="text"
      class="form-control"
      id="email"
      required
      v-model="user.email"
      name="email"
    />
  </div>

  <div class="form-group">
    <label for="password">Description</label>
    <input
      class="form-control"
      id="password"
      required
      v-model="user.password"
      name="password"
    />
  </div>
        <button @click="login1">Login</button>
    </div>
</div>

Script ->

<script>
import router from "../router"    
import http from "../http-common"    
export default {    
    data() {
        return {
                  user: {
    email: "", 
    password: ""
  }
        };
    },  
    methods: {    
        login1: () => {
            console.log(this.user.email);
        }  
    }    
}
</script>

In login1 function it console-logs undefined. This project was made using vue-router and vue, the newest version. It seems that the data returns just undefined. P.S: Sorry for such a question I'm just new to it. :)

Upvotes: 1

Views: 219

Answers (2)

Amaarockz
Amaarockz

Reputation: 4684

'this' cannot be referenced inside a arrow function since

Arrow functions perform lexical binding and uses the surrounding scope as the scope of this

so you need to remove the arrow definition like

methods: {    
        login1() {
            console.log(this.user.email);
        }  
    }  

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28434

The issue is that you're using an arrow-function which prevents this from referring to the Vue component:

new Vue({
  el:"#app",
  data() {
    return {
      user: {
        email: "", 
        password: ""
      }
    };
  },  
  methods: {    
    login1: function() {
      console.log(this.user);
    }  
  }   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">    
  <h2>Login</h2>    
  <div class="submit-form">
    <div class="form-group">
      <label for="email">Title</label>
      <input
        type="text"
        class="form-control"
        id="email"
        required
        v-model="user.email"
        name="email"
      />
    </div>
    <div class="form-group">
      <label for="password">Description</label>
      <input
        class="form-control"
        id="password"
        required
        v-model="user.password"
        name="password"
      />
    </div>
    <button @click="login1">Login</button>
  </div>
</div>

Upvotes: 2

Related Questions