DEV Community

Discussion on: 25 Vue Tips You Need to Know

Collapse
 
jvdl profile image
John van der Loo

One of your code samples isn't quite correct for tip #15. You've got:

// Do some processing beforehand
Object.entries(Icon.props).forEach((key, val) => {
  iconProps[`icon${key.toUpperCase()}`] = val;
});
Enter fullscreen mode Exit fullscreen mode

Where it should be:

// Do some processing beforehand
Object.entries(Icon.props).forEach(([key, val]) => {
  iconProps[`icon${key[0].toUpperCase() + key.substring(1)}`] = val;
});
Enter fullscreen mode Exit fullscreen mode

That tip is solid advice btw, I'm still discovering how to do all these things in a Vue.js world and apply all my React based knowledge in a useful way :-)

Re. tip #15, have you considered creating a file with prop types in it? This is something I've done in previous projects, particularly useful if you have the same/similar complex types used in multiple places. You could for example make the icon it's own prop type so that rather than passing down many attributes, you pass down a single object as an attribute:
e.g.
prop-types.js:

export const iconPropType = {
  type: {
    type: String,
    required: true
  },
  size: sizePropType,
  colour: {
    type: String,
    default: "#000"
  }
};
export const sizePropType = {
  type: String,
  default: "medium",
  validator: (size) => ["small", "medium", "large", "x-large"].includes(size)
};
Enter fullscreen mode Exit fullscreen mode

Icon.vue script:

import { iconPropType } from "./prop-types";
export default {
  props: {
    ...iconPropType,
  },
}
Enter fullscreen mode Exit fullscreen mode

Example usage:

import Icon from "./Icon";
import { iconPropType } from "./prop-types";

export default {
  components: { Icon },
  props: { icon: iconPropType },
};
Enter fullscreen mode Exit fullscreen mode

The icon can then be used as <Icon v-bind="icon" />

Collapse
 
michaelthiessen profile image
Michael Thiessen

Thanks for pointing this out! Fixed it in the article.

I haven't thought of using a separate file, but I think that would be very useful if you're using the same set of props a lot.

Vue prop types also allow any object with a constructor as a valid type, so you can create your own custom prop types that way. I've never experimented with that, but I'm sure there's a good use case for it.

Collapse
 
jvdl profile image
John van der Loo

Good to know about the alternate ways to use prop types, I hadn't considered using a constructable object, certainly that would be useful if you were passing around instances of said items rather than keeping a class/function in sync with a prop type definition.

In terms of using a separate file, indeed very useful for prop types that are used in multiple places (think Users, Avatars, Posts, etc.).