DEV Community

Cover image for How to set default inject/provide values in Vue
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

1 1

How to set default inject/provide values in Vue

Vue uses provide and inject as a method to send data down multiple levels without having to use properties - but did you know you can set default values for any injected data, should it not be injected in the first place? Let's look at how it works.

Setting default values with provide and inject in Vue

If you're not sure how provide and inject work, you can read about it here. By default, inject expects a default value to be set for a provide key - and if it's not, it'll throw a runtime error. As such, it's beneficial to set a default value so that a runtime error does not fire.

So let's look at an example. Say you provide some data in your parent like this:

<script setup>
    import { provide, ref } from 'vue'
    const message = ref('message');
    provide('myKey', message);
</script>
Enter fullscreen mode Exit fullscreen mode

If you then inject it somewhere, you can use the second argument to set the default value. For example:

<script setup>
    import { inject } from 'vue'
    const message = inject('myKey', 'the default value')
</script>
Enter fullscreen mode Exit fullscreen mode

In this example, if myKey cannot be found, the default value will be set to the default value instead. You can achieve the same thing with the Options API like so:

export default {
    inject: {
        message: {
            myKey: 'the default value'
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Setting default values for injectors in Vue is best practice, and helps prevent unexpected runtime errors. To learn more about Vue, click here.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay