1

I am currently writing a template for sending an email and after the function I want to conditionally render a success or error block. For some reason it is not working. The function itself is working, however neither success or error block is rendered. Please find my code below.

Template:

<form v-if="success==null" @submit.prevent="sendEmail" >
     ... //form code
    <input name="submit" type="submit" class="btn" value="send" />                                        
</form>
<b-alert variant="success" v-if="success">success</b-alert>
<b-alert variant="error" v-if="!success">error</b-alert>

Function:

   data() {
        return {
            success: null
        }
    },
    methods: {

    sendEmail: (e) => {
        ... // request code
        .then((result) => {
            this.success=true
            console.log('success')
        }, (error) => {
            this.success=false
            console.log('error')
        })
    }
}
coffee-and-code
  • 205
  • 2
  • 12

3 Answers3

3

I think you just need to use strict comparing for error block like:

success === false

There can be problems with !success because it's true for both null and false.

Also you can use string instead of boolean|null

var app = new Vue({
  el: '#app',
  data: {
    type: 'form',
    formData: {
      email: '',
    }
  },
  methods: {
    sendEmail() {
      if (this.formData.email) {
        this.type = 'success';
      } else {
        this.type = 'error';
      }

      setTimeout(() => this.type = 'form', 10000);
    }
  }
})
.success {
  color: green;
}

.error {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <form v-if="type === 'form'" @submit.prevent="sendEmail">
    <input type="email" v-model="formData.email" />
    <button type="submit">Submit</button>
  </form>

  <div v-if="type === 'success'" class="success">Success!</div>
  <div v-if="type === 'error'" class="error">Error!</div>
</div>
Asimple
  • 650
  • 3
  • 8
2
  1. Are you sure your success/error handler are called ?/
  2. In your method sendEmail you should define define it without an arrow function
sendEmail (e) {
       ... // request code
       .then((result) => {
           this.success=true
           console.log('success')
       }, (error) => {
           this.success=false
           console.log('error')
       })
   }
2

Try this

<b-alert :variant="success ? 'success' : 'error'" v-if="success!=null" :key="success">
   <span v-if="success">success</span>
   <span v-else>error</span>
</b-alert>
Beshambher Chaukhwan
  • 1,418
  • 2
  • 9
  • 13