This story on HackerNoon has a decentralized backup on Sia.
Transaction ID: zhjit6YLHsCyOm5lf-sPxG6BM94DtXM1uhM_OBM5ccY
Cover

Setting Default Inject/Provide Values in Vue

Written by @smpnjn | Published on 2022/8/1

TL;DR
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. 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.

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>

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>

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'
        }
    }
}

Setting default values for injectors in Vue is best practice, and helps prevent unexpected runtime errors.


Also published here.

[story continues]


Written by
@smpnjn
Product, Engineering, Web

Topics and
tags
javascript|vuejs|javascript-development|web-development|javascript-frameworks|programming|programming-languages|java-programming
This story on HackerNoon has a decentralized backup on Sia.
Transaction ID: zhjit6YLHsCyOm5lf-sPxG6BM94DtXM1uhM_OBM5ccY