Home> Web Front-end> Vue.js> body text

Detailed explanation of the method of dynamically adding class names in Vue

青灯夜游
Release: 2020-11-03 18:01:39
forward
3631 people have browsed it

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. Whateverclassnameevaluates 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

Copy after login

Dynamic classes are very similar, but we have to use Vue’s special attribute syntaxv-bind, in order to bind the JS expression to our class:

Copy after login

Here you will notice that we have to add extra quotes around the dynamic class name.

This is because thev-bindsyntax accepts whatever we pass as a JS value. Adding quotes ensures Vue treats it as a string.

Vue also has a shorthand syntax forv-bind:

Copy after login

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:

 export default { data() { return { theme: 'blue-theme', }; } }; ---------------------------------------- .blue-theme { color: navy; background: white; }
Copy after login

In this case,themeis the content we will apply The variable of the class name.

Conditional class names

Sincev-bindcan 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.

Copy after login

IfdarkModeistrue,dark-themewill be used as our class name. Otherwise, we chooselight-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

Copy after login

We use the array to set two dynamic classes on this element name. The value offontThemeis a class name that will change the appearance of the font. In the previous example, we can still use thedarkModevariable to switch betweendark-themeandlight-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:

Copy after login

Our object contains two keys:dark-themeandlight-theme. Similar to the logic we implemented previously, we want to switch between these themes based on the value ofdarkMode.

WhendarkModeistrue,dark-themewill be applied to our elements as a dynamic class name. Butlight-themwill not be applied because the!darkModevalue isfalse.

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

Copy after login

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:classattribute as before

Copy after login

The reason this works is because Vue is directly on the root element ofMovieListSetup class.

When you setpropson a component, Vue compares these props to the props specified by the component in itspropssection. If there is a match, it will be passed as regular props. Otherwise, Vue will add it to the root DOM element.

Here, sinceMovieListdoes not specify theclassattribute, 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 aButtoncomponent that provides 20 different CSS styles for all different types of buttons.

你可能不想花一整天的时间把每一项都写出来,也不想把开关的逻辑都写出来。相反,我们将动态生成要应用的类的名称。

 export default { data() { return { theme: 'blue-theme', }; } }; .blue-theme { color: navy; background: white; }
Copy after login

我们可以设置一个变量来包含我们想要的任何类名的字符串。如果我们想对Button组件执行此操作,则可以执行以下简单操作:

 export default { props: { theme: { type: String, default: 'default', } } }; .default {} .primary {} .danger {}
Copy after login

现在,使用Button组件的任何人都可以将theme属性设置为他们想要使用的任何主题。

如果没有设置任何类,它将添加.default类。如果将其设置为primary,则会添加.primary类。

使用计算属性来简化类

最终,模板中的表达式将变得过于复杂,并将开始变得非常混乱和难以理解。幸运的是,我们有一个简单的解决方案,就是使用计算民属性:

 export default { computed: { class() { return darkMode ? 'dark-theme' : 'light-theme'; } } };
Copy after login

这不仅易于阅读,而且还可以轻松添加新功能并在将来进行重构。

英文原文地址:https://forum.vuejs.org/t/add-a-dynamically-generated-class-name-to-components-class-attribute-from-mixin/27626

为了保证的可读性,本文采用意译而非直译。

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程教学!!

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!

Related labels:
vue
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn