ctf0
ctf0

Reputation: 7579

how to override a computed property through $emit in vuejs

i have a form which have a couple of comps for inputs and inside each there is another comp for error, so i have

// input comp
<template></template>

<script>
    import Store from '../../store'

    export default {
        props:['errors'],
        data() {
            return {
                input: ''
            }
        },
        computed: {
            showError() {
                if (this.errors && !this.input) {
                    return true;
                }
            }
        }
    }
</script>

// error comp
<template>
    <span class="help-block">
        <strong v-for="error in errors">
            {{ error }}
        </strong>
    </span>
</template>

<script>
    export default {
        props: ['errors'],
        watch: {
            errors: (val) => {
                this.$emit('newError')
            }
        },
    }
</script>

// display the error
<form-errors :errors="errors" v-if="showError" v-on:newError="showError = !showError"></form-errors>

so what am after is

  1. get the error watch to actually work as so far i don't know how to hook into the component update

  2. how to override the computed prop of showError

Upvotes: 1

Views: 3902

Answers (1)

Saurabh
Saurabh

Reputation: 73609

No you can not overwrite the computed property like this: showError = !showError, You have to use some other approach.

Given that you want to show both errors: errors related to form input and error coming from backend: You can have following structure of your error variable:

errors: { 
  "backendErrors": [], 
  "formErrors" : [] 
}

Now you can have your computed property show error like following:

showError() { 
   if (this.errors.backendErrors || (this.errors.formErrors && !this.input) ) { 
      return true; 
   } 
   else{
      return false
   }
}

ot whatever other logic suits you.

Upvotes: 1

Related Questions