Detailed explanation of the method of dynamically adding class names in Vue
Being able to add dynamic class names to components is a very powerful feature. It makes it easier for us to write custom themes, add classes based on the component's state, and also write different variations of components that depend on styles.
Adding a dynamic class name is as simple as adding prop :class="classname"
to the component. Whatever classname
evaluates to, will be the class name added to the component.
Of course, there is a lot more we can do with dynamic classes in Vue. In this article, we will discuss a lot:
- Using static and dynamic classes in Vue
- How to use regular JS expressions to evaluate our classes
- Array syntax for dynamic class names
- Object syntax
- Quickly generate class names
- How to use dynamic class names on custom components
Static and dynamic classes
In Vue, we can add static classes and dynamic classes to components.
Static classes are those boring classes that never change, they will always be present in the component. On the other hand, we can add and remove dynamic classes from the application.
Adding a static class is exactly the same as doing it in regular HTML
<template> <span class="description"> This is how you add static classes in Vue. </span> </template>
Dynamic classes are very similar, but we have to use Vue’s special attribute syntax v-bind
, in order to bind the JS expression to our class:
<template> <span v-bind:class="'description'"> This is how you add static classes in Vue. </span> </template>
Here you will notice that we have to add extra quotes around the dynamic class name.
This is because the v-bind
syntax accepts whatever we pass as a JS value. Adding quotes ensures Vue treats it as a string.
Vue also has a shorthand syntax for v-bind
:
<template> <span :class="'description'"> This is how you add static classes in Vue. </span> </template>
What’s really amazing is that you can even have both static and dynamic classes on the same component . Static classes are used for content that we know will not change, such as positioning and layout, and dynamic classes are used for things like themes:
<template> <span class="description" :class="theme" > This is how you add static classes in Vue. </span> </template> export default { data() { return { theme: 'blue-theme', }; } }; ---------------------------------------- .blue-theme { color: navy; background: white; }
In this case, theme
is the content we will apply The variable of the class name.
Conditional class names
Since v-bind
can accept any JS expression, we can do some really cool things with it. My favorite is using ternary expressions in templates, it tends to be very clean and readable.
<template> <span class="description" :class="darkMode ? 'dark-theme' : 'light-theme'" > This is how you add dynamic classes in Vue. </span> </template>
If darkMode
is true
, dark-theme
will be used as our class name. Otherwise, we choose light-theme
.
Use array syntax
If you need to add many different classes dynamically, you can use arrays or objects. Both methods are useful, let's look at the array method first.
Because we are just calculating a JS expression, we can combine the expression we just learned with the array syntax
<template> <span class="description" :class="[ fontTheme, darkMode ? 'dark-theme' : 'light-theme', ]" > This is how you add dynamic classes in Vue. </span> </template>
We use the array to set two dynamic classes on this element name. The value of fontTheme
is a class name that will change the appearance of the font. In the previous example, we can still use the darkMode
variable to switch between dark-theme
and light-theme
.
Using object syntax
We can even use objects to define lists of dynamic classes, which gives us more flexibility.
For any key/value pair whose value is true, it will use the key as the class name. Let's look at an example of object syntax:
<template> <span class="description" :class="{ 'dark-theme': darkMode, 'light-theme': !darkMode, ]" > This is how you add dynamic classes in Vue. </span> </template>
Our object contains two keys: dark-theme
and light-theme
. Similar to the logic we implemented previously, we want to switch between these themes based on the value of darkMode
.
When darkMode
is true
, dark-theme
will be applied to our elements as a dynamic class name. But light-them
will not be applied because the !darkMode
value is false
.
Now we have covered the basics of dynamically adding classes to Vue components. So how can I do this using my own custom component?
Used with custom components
Suppose we have a custom component in the app
<template> <MovieList :movies="movies" :genre="genre" /> </template>
What should we do if we want to dynamically add a class that will change the theme manage? it's actually really easy.
We just need to add the :class
attribute as before
<template> <MovieList :movies="movies" :genre="genre" :class="darkMode ? 'dark-theme' : 'light-theme'" /> </template>
The reason this works is because Vue is directly on the root element of MovieList
Setup class.
When you set props
on a component, Vue compares these props to the props specified by the component in its props
section. If there is a match, it will be passed as regular props. Otherwise, Vue will add it to the root DOM element.
Here, since MovieList
does not specify the class
attribute, Vue knows it should be set on the root element.
However, we can do some more advanced things with dynamic class names.
Generate class names quickly
We have covered many different ways to dynamically add or remove class names. But what about the dynamically generated class name itself?
Suppose there is a Button
component that provides 20 different CSS styles for all different types of buttons.
你可能不想花一整天的时间把每一项都写出来,也不想把开关的逻辑都写出来。相反,我们将动态生成要应用的类的名称。
<template> <span class="description" :class="theme" > This is how you add static classes in Vue. </span> </template> export default { data() { return { theme: 'blue-theme', }; } }; .blue-theme { color: navy; background: white; }
我们可以设置一个变量来包含我们想要的任何类名的字符串。如果我们想对Button
组件执行此操作,则可以执行以下简单操作:
<template> <button @click="$emit('click')" class="button" :class="theme" > {{ text }} </button> </template> export default { props: { theme: { type: String, default: 'default', } } }; .default {} .primary {} .danger {}
现在,使用Button
组件的任何人都可以将theme
属性设置为他们想要使用的任何主题。
如果没有设置任何类,它将添加.default
类。如果将其设置为primary
,则会添加.primary
类。
使用计算属性来简化类
最终,模板中的表达式将变得过于复杂,并将开始变得非常混乱和难以理解。幸运的是,我们有一个简单的解决方案,就是使用计算民属性:
<template> <MovieList :movies="movies" :genre="genre" :class="class" /> </template> export default { computed: { class() { return darkMode ? 'dark-theme' : 'light-theme'; } } };
这不仅易于阅读,而且还可以轻松添加新功能并在将来进行重构。
英文原文地址:https://forum.vuejs.org/t/add-a-dynamically-generated-class-name-to-components-class-attribute-from-mixin/27626
为了保证的可读性,本文采用意译而非直译。
相关推荐:
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of Detailed explanation of the method of dynamically adding class names in Vue. For more information, please follow other related articles on the PHP Chinese website!

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment