D
D
diafree2019-07-17 12:13:05
Vue.js
diafree, 2019-07-17 12:13:05

Vue: how to change component state after fetching data (Fetch)?

Good afternoon.
I'm just starting to learn Vue, I ran into such a problem - there is a component (authorization form), on the submit event I send / receive data via the API (Fetch).
Actually the question is: how to change the state of the component after receiving the data, i.e. hide/delete it, because is it no longer needed and render another component?
Tried to change this.show = false but this variable is undefined

Vue.component('auth-form', {
  template: `
    <div>
      <form @submit.prevent="onSubmit" v-if="show">
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            	<span class="input-group-text" id="basic-addon1"><i class="far fa-user-circle"></i></span>
          </div>
          <input name="name" type="text" class="form-control" v-model="login" placeholder="Логин">
        </div>
        <div class="input-group mb-3">
          <div class="input-group-prepend">
            	<span class="input-group-text" id="basic-addon1"><i class="fas fa-unlock-alt"></i></span>
          </div>
          <input name="password" type="password" class="form-control" v-model="password" placeholder="Пароль">
        </div>
        <div class="text-right"><button type="submit" class="btn btn-primary">Авторизоваться</button></div>
      </form>
    </div>
  `,
  data() {
    return {
      login: null,
      password: null,
      show: true
    }
  },
  methods: {
    onSubmit() {
      let data = {
        "login": this.login,
        "password": this.password
      }

      fetch('http://url', {
        method: 'post',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
        mode: 'cors',
      }).then(function(response) {
this.show = false;  //<-- undefined
        return response.json();
      }).then(function(response) {
        console.log(response);
      }).catch(alert);

      this.login = null
      this.password = null
    }
  }
})

var app = new Vue({
  el: '#app'
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2019-07-17
@diafree

this is undefined because .then is passed a function with its context
.then(function() {})
.then(() => {})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question