Home  >  Article  >  Web Front-end  >  Detailed explanation of the method of dynamically adding class names in Vue

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

青灯夜游
青灯夜游forward
2020-11-03 18:01:393638browse

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="&#39;description&#39;">
    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="&#39;description&#39;">
    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: &#39;blue-theme&#39;,
    };
  }
};
----------------------------------------
.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 ? &#39;dark-theme&#39; : &#39;light-theme&#39;"
  >
    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 ? &#39;dark-theme&#39; : &#39;light-theme&#39;,
    ]"
  >
    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="{
      &#39;dark-theme&#39;: darkMode,
      &#39;light-theme&#39;: !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 ? &#39;dark-theme&#39; : &#39;light-theme&#39;"
  />
</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: &#39;blue-theme&#39;,
    };
  }
};

.blue-theme {
  color: navy;
  background: white;
}

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

<template>
  <button
    @click="$emit(&#39;click&#39;)"
    class="button"
    :class="theme"
  >
    {{ text }}
  </button>
</template>

export default {
  props: {
    theme: {
      type: String,
      default: &#39;default&#39;,
    }
  }
};

.default {}

.primary {}

.danger {}

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

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

使用计算属性来简化类

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

<template>
  <MovieList
    :movies="movies"
    :genre="genre"
    :class="class"
  />
</template>

export default {
  computed: {
    class() {
      return darkMode ? &#39;dark-theme&#39; : &#39;light-theme&#39;;
    }
  }
};

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

英文原文地址: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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete