Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

vue.js - 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. :)

question from:https://stackoverflow.com/questions/65886823/vue-every-object-in-data-is-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...