Vue, how to use prop as a class name

Sometimes, you pass a prop to a component and you want to use the prop value as the class name. How to do it?

Suppose you have a Car component.

You want to add a class to its output based on the props.

So maybe the prop is calledcolor, You can use it like this in other parts of the application:

<Car color="red">
<Car color="blue">

In your Car component, you first need to declare the color prop:

export default {
  name: 'Car',
  props: {
    color: String

Then you can use it in the template section:

  <div :class="color"></div>

If you want to addcarThe class, plus the class determined by the color props, can use the following syntax:

  <div :class="['car', color]"></div>

Happy coding!

Download mine for freeVue manual

More vue tutorials: