A Better Way To Create Vue Components With Props Using TypeScript

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • The defineProps in Vue can be used in a few ways using TypeScript. In this video I discuss 2 different ways of using props and what I think is best using Zod.
    👉 Check out my last video on Styling with Tailwind
    • Style Your App With Ta...
    👉Sign up for my mailing list and get neat stuff!
    bit.ly/3Umk7sW
    👉 Need some help with a project, level up your skills, React, Next, Vue, or Nuxt? Check out my 1-on-1 mentoring!
    mentors.to/erik
    Links:
    zod.dev/?id=installation
    blog.vuejs.org/posts/vue-3-3#...
    0:00 defineProps problem
    0:36 inherit props explained and $attrs
    02:00 using defineProps
    03:30 adding validations
    04:25 using defineProps with TS
    06:23 adding in default values with destructuring
    08:10 adding in validation with Zod

Komentáře • 53

  • @ProgramWithErik
    @ProgramWithErik  Před 5 měsíci +2

    How do you use props?

  • @ilaydelrey3122
    @ilaydelrey3122 Před 2 měsíci +1

    its nice to have a youtuber here that uses vue3 with the most latest syntax ( script setup) and keeps teaching about new concept and ideas! Will definetly keep checking this channel out because its a scarce vue resource

  • @Saeid-Za
    @Saeid-Za Před 5 měsíci +2

    Thanks for the tip, one note that should be considered is that the defineProps validation is in development only and has no runtime cost in production mode.
    The solution provided here does have runtime cost in production mode.
    Another, less related note is that Zod does not support adding custom multi-language validation errors in a developer friendly way, thats why I always go back to a simpler way of validating forms in general.
    But all and all, a lovely library.
    Thanks for the video ❤️

    • @ProgramWithErik
      @ProgramWithErik  Před 4 měsíci +2

      Thanks for the feedback!

    • @icavalheiro
      @icavalheiro Před 19 dny

      well, if we wrap the validations in a reusable class as erik suggested, it makes this even better, cus we can control that. For example, my apps always make use of a debug flag ("?debug" in the url) that allows me to debug stuff in production if I need, with this approach I could validate the inputs if debug==true, and jsut retun; in case its not.

  • @mandin182
    @mandin182 Před 5 měsíci

    I've been using with composition api I basically have a const props with WithDefaults and defineProps for each component, there use my interfaces to type the props, just a few of them I use defaultvalues, I've been using Yup as a validator tool, very similar to zod as I can see, cheers! love your videos

  • @guhacdc
    @guhacdc Před 5 měsíci

    Nice work, tks. I use yup for validations,

  • @Kingside88
    @Kingside88 Před 5 měsíci +1

    Great video! Thank you, Erik.
    In C# we have a Package called Fluentvalidation. It has similar functions for validations.
    Usually you create a class UserValidation where you abstract the validation logic.
    Inside you pass rules like RuleFor(x=> x.Name).NotNull().WithMessage("Name should not be null").
    Then in the save user process you create an instance of this class and pass your user object.
    The result instance has a property if it has issues and the error messages. So you can pass it to the frontend.
    I think with Zod it should be possible to do a similar approach with compositions.

  • @johnnydriesen7575
    @johnnydriesen7575 Před 5 měsíci +1

    Thanks again for sharing your knowledge, Erik.
    I'm REALLY happy to see you're using ZOD.
    You mentioned "we can use ZOD for form validation as well"
    It would be great to see how you're doing form validation with ZOD...
    More in particular... Which is the preferred way to combine "error" messages with I18N ?
    In other words... Depending on the chosen language in the app, the user has to see the message "firstname is a required field" or "voornaam is een verplicht veld"...
    I hope you got my point...
    Thanks in advance for coming back on this...

    • @ProgramWithErik
      @ProgramWithErik  Před 5 měsíci +1

      Will do! And good to see you commenting again !

  • @wvovaw3052
    @wvovaw3052 Před 5 měsíci +1

    Zod is good for server-side use, because we usually don't care about the size of the server-side application bundle.
    But for client-side validation, Valibot looks better. It has almost the same API as Zod, but it saves bundle size.

    • @wvovaw3052
      @wvovaw3052 Před 5 měsíci

      And I'm not sure I'd want to apply this runtime validation to every component, but it's a nice addition for some cases tho

  • @miguelcassimiro8103
    @miguelcassimiro8103 Před 5 měsíci

    Hi Erik, it’s quite interesting, Zod really make the thing much more easier. I just think the original way to type the props are really good because it came with less complexity. Otherwise using the Typescript is really a good way to do that.
    Using schemas worth in big scenarios. The original way is quite good and completed.

  • @iUmerFarooq
    @iUmerFarooq Před 5 měsíci

    Next tutorial on Vuejs+Firebase 🔥

  • @SXsoft99
    @SXsoft99 Před 5 měsíci +2

    i just prefer the vue props type definition, it's just clean

  • @niknik6420
    @niknik6420 Před 5 měsíci

    👋Hello! What theme do you use in the vs code?

  • @daltonj507
    @daltonj507 Před 5 měsíci +1

    Great video, this one was so packed with good info and tips. Thanks!

  • @Voltra_
    @Voltra_ Před 5 měsíci +2

    Using zod (or just vue-types) is pretty cool tho

  • @andreich1980
    @andreich1980 Před 4 měsíci

    Does class change work similar if the class you apply to the component is defined in Tailwind CSS AFTER the initial class you defined inside the component? I guess you DO NEED to use twMerge in this case.

  • @ivansabolic6823
    @ivansabolic6823 Před 2 měsíci

    I would really love the prop validation on the compile side (vue, vite combination).. vueTsc is not working with options API and also not with more complex types (Classes).. from the console.warn perspective is (which is here mentioned) good only on runtime.. if you have 1 component used in multiple places (or inside the library) this is not enough.. also using vscode plugin is only checking opened files which is also not good enough.. I think react/vite/typescript is more mature for now.. sadly.. Vue 2 with webpack had this options...

  • @ColinRichardson
    @ColinRichardson Před 5 měsíci +3

    Is destructuring still reactive? Because it doesn't look like it is.
    If it "is magically" reactive, I am unsure if that is good or bad.
    If the code reads as one thing but is actually something else.....

    • @Nerlon93
      @Nerlon93 Před 5 měsíci

      props aren't reactive. you'd have to go with toRef or maybe defineModel

    • @ColinRichardson
      @ColinRichardson Před 5 měsíci

      @@Nerlon93 normally the `const prop = defineProps()` object is reactive, and you read the properties of the prop object.
      But I have never played with the experimental vite config before, and don't feel like setting up a whole environment to test..
      If `const { test = 'hello' } = defineProps()` isn't reactive at all, and is now a 1 hit pony, then this is a massive no no of a pattern..
      but, as I said, I haven't played with the experimental config, so if it actually does return a ref, then all is well. but then it makes no sense with the `= 'hello' ` part.. It would basically be magic by obscurity, which is terrible..
      It's bad enough that `defineProp` and `defineEmits` internals are already kinda `magic` to begin with.

    • @Nerlon93
      @Nerlon93 Před 5 měsíci

      ​@@ColinRichardson how is it reactive?
      you have props = defineProps(text)
      you cant have on this component a text prop is read only. it's not reactive

    • @ColinRichardson
      @ColinRichardson Před 5 měsíci

      @@Nerlon93 I think you are misunderstanding the meaning of reactive vs immutable. `isReactive(props)` props is a `readonly` `reactive` object. When the props are altered from the outside, it triggers the reactive system into updating.
      I've just had a very quick look at that is going on with destructureProps, it seems it makes it work like a fake ref. I say fake, because it cannot be passed into composables that expect a ref. And it only keeps it reactivity within the context of the setup function.. This seems counterintuitive since it's just more wishy washy hidden magic going on.
      I will be recommending our codebase stick to `toRefs()`

    • @ProgramWithErik
      @ProgramWithErik  Před 5 měsíci

      Good question, maybe I should have made this more clear. It does keep reactivity , it's a new feature with 3.3 -> blog.vuejs.org/posts/vue-3-3#reactive-props-destructure

  • @DontFollowZim
    @DontFollowZim Před 5 měsíci

    I definitely like defining props via the type argument. Never liked withDefaults because then you end up defining many of the same properties twice. Same is even more true with destructuring, which is annoying, but at least you get the benefit of the toRefs as well with it

  • @chambaderaphael8946
    @chambaderaphael8946 Před 5 měsíci +4

    Zod IS Magic, in vue, in graphql backend, everywhere

  • @2dogs1car0pb
    @2dogs1car0pb Před 5 měsíci

    Thanks. very good info. Will update my doggie app asap

  • @studiowebselect
    @studiowebselect Před 5 měsíci

    You cannot add zod on defineProps because zod is at runtime and defineprops before at "build time"

  • @FNXTproductionz
    @FNXTproductionz Před 5 měsíci

    It's a bummer zod infering doesn't work with Props. It would also be little bit conficlting when setting a default value using Zod using the .default() function, the infered type would have tha value as not nullable. But the Prop would be optional :D

  • @user-sj7tf2yv3m
    @user-sj7tf2yv3m Před 5 měsíci

    Vue Props validation работает только в dev режиме.
    Zod очень тяжёлая библиотека для проверки props

  • @CyanidePierce90
    @CyanidePierce90 Před 5 měsíci +7

    Hate the way programming is going sometimes.

  • @Voltra_
    @Voltra_ Před 5 měsíci

    Reminder that at first, and until recently, Vue 3 didn't support using imported types in props (e.g. extending from it)

  • @wwizer
    @wwizer Před 5 měsíci

    We use vee validate at work for forms but this is cool

  • @Tarabass
    @Tarabass Před 5 měsíci

    defineProps()

  • @user-sj7tf2yv3m
    @user-sj7tf2yv3m Před 5 měsíci +1

    Давайте признаем, что у Vue осталось много проблем с DX и Typescript

  • @CabbageShop
    @CabbageShop Před 5 měsíci

    As @wvovaw3052 says Valibot is better for front end stuff due to the smaller bundle size.
    I've been able to build a type from a valibot schema i've created then use it as a prop type. For example
    ```vue
    import * as z from 'valibot'
    //Define the clItemSchema
    const clItemSchema = z.object({
    id: z.number(),
    heading: z.string(),
    mainContent: z.string(),
    email: z.string([z.email()])
    })
    //Use the clItemSchema to define the type of the clItem
    type CLItem = z.Input
    const { clItem } = defineProps()
    //Try to parse the clItem using the clItemSchema
    try {
    z.parse(clItemSchema, clItem)
    } catch (error) {
    console.log("Prop clItem is invalid:", error)
    }
    ```
    It has a similar api to Zod so if you import it as 'z' copilot thinks that's what your using and fills stuff in for you

  • @виртуоз_ру
    @виртуоз_ру Před 5 měsíci

    👍👍👍👍👍👍👍👍👍👍👏👏👏👏👏👏👏👏🙋‍♂🙋‍♂🙋‍♂

  • @user-sj7tf2yv3m
    @user-sj7tf2yv3m Před 5 měsíci

    sxzz/vue-simple-props