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:
<script>
export default {
name: 'Car',
props: {
color: String
}
}
</script>
Then you can use it in the template section:
<template>
<div :class="color"></div>
</template>
If you want to addcar
The class, plus the class determined by the color props, can use the following syntax:
<template>
<div :class="['car', color]"></div>
</template>
Happy coding!
Download mine for freeVue manual
More vue tutorials:
- Vue.js overview
- Vue.js CLI: Learn how to use it
- Vue.js development tools
- Configure VS code for Vue development
- Create your first application with Vue.js
- Vue.js single file component
- Vue.js templates and interpolation
- Vue.js instructions
- Vue.js method
- Vue.js calculated attributes
- Use CSS to style Vue.js components
- Vue.js observer
- Vue method vs observer vs calculated property
- Vue.js filter
- Vue.js components
- Vue.js slot
- Vue.js component props
- Vue.js activities
- Vue.js component communication
- Vuex, Vue.js state manager
- Vue, use a component inside another component
- Vue, how to use prop as a class name
- How to use SCSS with Vue.js single file component
- Use Tailwind in Vue.js
- Vue router
- Dynamically display Vue components
- Vue.js cheat sheet
- Use Vuex to store Vue data to localStorage
- How to use Vue dynamic application class
- Vue, how to use the v model
- Vue, why data must be functions
- Roadmap to become a Vue.js developer in 2020