MSkred
MSkred

Reputation: 11

Vue error handler : Hide component whene there is an error in it

I want to hide a component if there is an error in it.

To do this, I use the following function.

Vue.confgi.error = function(err, vm, info) {

// The probleme is there I don't find the solution for just hide the component if there is an error.

// MY BAD SOLUTION 
vm.$el.parentNode.removeChild(vm.$el)
vm.$el.parentNode.removeChild(vm.$el)

}

If I write it only once I don't have an error in the console but the component is not hiding. When I put it 2 times as above I have the desired result but this in the console.

error-handler.js:10 Uncaught (in promise) TypeError: Cannot read property 'removeChild' of null
    at vue__WEBPACK_IMPORTED_MODULE_0__.default.config.errorHandler (error-handler.js:10)
    at _callee$ (client.js:151)
    at tryCatch (runtime.js:63)
    at Generator.invoke [as _invoke] (runtime.js:293)
    at Generator.eval [as next] (runtime.js:118)
    at asyncGeneratorStep (asyncToGenerator.js:5)
    at _next (asyncToGenerator.js:27)
    at eval (asyncToGenerator.js:34)
    at new Promise (<anonymous>)
    at eval (asyncToGenerator.js:23)

Thank for your help !

Upvotes: 0

Views: 1023

Answers (1)

Tim
Tim

Reputation: 1229

If the component with the error is a child of another component, then you could have the erroring component emit an event to it's parent component to hide.

HideOnError.vue

<template>
  <div class="hide-on-error">
    <h4>HideOnError.vue</h4>
    <button type="button" class="btn btn-primary" @click="processError">Click to hide me</button>
  </div>
</template>

<script>
  export default {
    methods: {
      processError() {
        this.hideMe();
      },
      hideMe() {
        this.$emit('hide-child-event');
      }
    }
  }
</script>

Parent.vue

<template>
  <div class="parent">
    <h3>Parent.vue</h3>
    <hr>
    <hide-on-error v-if="showChild" @hide-child-event="handleHideChildEvent" />
  </div>
</template>

<script>
  import HideOnError from './HideOnError.vue'
  export default {
    components: {
      HideOnError
    },
    data() {
      return {
        showChild: true
      }
    },
    methods: {
      handleHideChildEvent() {
        this.showChild = false;
      }
    }
  }
</script>

Upvotes: 1

Related Questions