Gustavo Lopes
Gustavo Lopes

Reputation: 4174

How can I catch Vue Warn '[Vue warn]: Missing required prop'

I have a component set like:

export default {
  props: {
    prop1: {
      type: String,
      required: true,
    },
  }
}

If I don't provide the required prop1, Vue emits a warning like

[Vue warn]: Missing required prop: "prop1"

I'm wondering, how can I catch this warn and do something about it?


My use case is using the component as a page, with props: true on the VueRouter.

If it's a navigation inside my application using $router.push({params: {prop1: 'whatever' }}), everything works well.

But if the user lands on the url, the props won't be set and I want to display a message or redirect him or whatever.


I know I can make the props not required and validate it on the mounted, but it seems duplicating code.

I'm imagining something like Component.mountedError()

Upvotes: -1

Views: 2781

Answers (1)

Joseph
Joseph

Reputation: 6269

you could work around the validator method by adding a default value and check if the props still have this default value throw a custom error and return with true to disallow Vue to throw its own warning like this

Vue.component('alert', {
  template: `
    <h1>{{ title }}</h1> 
  `,
  props: {
    title: {
      type: String,
      default: 'default',
      validator: function(value) {
        if (value === 'default') {
          console.log('Custom error message here')
          alert('props required');
        }
        return true;
      }
    }
  }
})



let vm = new Vue({
  el: '#app'
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <alert />
</div>

Upvotes: 2

Related Questions