Slide 1

Slide 1 text

Vue’s “Provide / Inject” An advanced pattern that isn’t very useful!

Slide 2

Slide 2 text

A thought experiment https://codepen.io/isaaclyman/pen/JayZWb You’re building a component library that provides and components. You know it will be easier to code if v-option could know about the “type” prop you passed to v-menu.

Slide 3

Slide 3 text

How would you make that work?

Slide 4

Slide 4 text

Possible solutions - Make the user pass all the necessary data to every single component ugh - A shared JavaScript singleton with some, uh, IDs and stuff to keep the component reusable - Something with scoped slots this isn’t what scoped slots are for but yolo i guess - Any other ideas?

Slide 5

Slide 5 text

Provide/Inject: What is it? - A pattern for sneaking stuff around in Vue without using props. - A way to send secret messages to child and grandchild components.

Slide 6

Slide 6 text

Why would I ever use it? If you’re building a Vue component library and it simplifies the user interface.

Slide 7

Slide 7 text

Why would I ever use it? (continued) - You are providing two black-box components - One of them is meant to be used inside of the other one - You want the outer one to share data with the inner one - OR, you want the inner one to emit events to the outer one - The user would probably be annoyed if they had to pass the same data as props to both components

Slide 8

Slide 8 text

Let’s try it out!

Slide 9

Slide 9 text

Back in days of yore (Vue.js v0.11) var myObject = { msg: ‘hello’ }; {{ msg }}

Slide 10

Slide 10 text

Let’s build a component library that does this I’m gonna be GitHub Famous!™

Slide 11

Slide 11 text

First, the interface var myObject = { msg: ‘hello’ };

Slide 12

Slide 12 text

Then the components
export default { props: { scoped: { required: true } }, provide() { return { scoped: this.scoped } } } {{ scoped[property] }} export default { props: { property: { required: true } }, inject: ['scoped'] }

Slide 13

Slide 13 text

Check it out https://codepen.io/isaaclyman/pen/gjzvKd

Slide 14

Slide 14 text

Can you think of other use cases?

Slide 15

Slide 15 text

See it in action! https://github.com/isaaclyman/Viano/blob/master/src/components/Part.vue https://github.com/isaaclyman/Viano/blob/master/src/components/Note.vue

Slide 16

Slide 16 text

Isaac Lyman Web: http://isaaclyman.com Email: [email protected] Twitter: @isaacandsuch