如何使用 Vue.js 基于 props 向元素添加多个类?

Eri*_*ric 3 html javascript css vue.js vuejs2

先看我的代码,理解问题。

<template>
    <div class="header" 
        :class="flat ? 'flat' : null"
        :class="app ? 'app' : null">
    </div>
</template>

<script>
    export default {
        props: {
            flat: {
                type: Boolean,
                default: false
            },
            app: {
                type: Boolean,
                default: false
            }
        }
    }
</script>

<style lang="scss">
    .header {
        width: 100%;
        height: 55px;
        background: white;
        box-shadow: 0px 3px 6px #ccc;
        transition: .8s ease-in-out;

    }
    .flat {
        box-shadow: none;
    }
    .app {
        padding-left: 10%;
        padding-right: 10%;
    }

</style>
Run Code Online (Sandbox Code Playgroud)

所以正如你在这里看到的,我是否有我的平面道具,它会触发一个平面类来显示一个盒子阴影与否。但我也希望有人触发 app 道具,该道具将在标题中放置一些填充。

这里的问题是你不能在一个元素中放置多个 :classes 。有什么解决办法吗?

Bou*_*him 5

尝试将它们组合在同一个类属性中,如下所示:

<div class="header"
  :class="{ 'flat':flat,'app' : app}"
>header</div>
Run Code Online (Sandbox Code Playgroud)

official documentation


Jai*_*ina 5

有几种方法可以实现您的目标,Vue 在这方面非常出色。

1. 传递类数组

<div 
  class="header" 
  :class="[flat ? 'flat' : null, app ? 'app' : null]"
></div>
Run Code Online (Sandbox Code Playgroud)

2.传递一个对象

<div 
  class="header" 
  :class="{flat: flat, app: app}"
></div>
Run Code Online (Sandbox Code Playgroud)

在这里,只有具有真实值的道具才会被设置为类。

2.1 如果你使用 ES6 你可以使用对象属性值的简写

<div 
  class="header" 
  :class="{flat, app}"
></div>
Run Code Online (Sandbox Code Playgroud)

奖金

如有必要,您也可以混合使用 1 和 2(我有时需要它)

<div 
  class="header" 
  :class="[{flat, app}, someOtherClass]"
></div>
Run Code Online (Sandbox Code Playgroud)


Aba*_*ara 1

您可以创建一个返回与 @Boussadjra Barhim 答案相同的对象的方法。

//if value is evaluated into true, the key will be a part of the class
setClass: function(flat, app){
    return {
      flat: flat, 
      app: app
    }
}
Run Code Online (Sandbox Code Playgroud)

使用它通过

<element :class="setClass(flat, app)" />
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,您可以编写其他更长的代码(不会丑化模板)来在返回对象之前处理值

setClass: function(flat, app){
    //do something else with inputs here
    return {
      flat: flat, 
      app: app
    }
}
Run Code Online (Sandbox Code Playgroud)