Vue中:class绑定多参数报错,如何正确拼接动态类名?
解决Vue :class绑定中动态拼接类名的报错问题
你遇到的报错是因为Vue的:class对象语法要求每个成员必须是**类名: 布尔值**的键值对结构,而你写的'animation__placeholder--' + animation只有键名没有对应的值,不符合语法规则,所以提示需要冒号。
下面是几种正确的实现方式:
方式1:数组+对象组合语法
把动态拼接的类名放在数组里,条件类放在对象里,Vue支持这种混合写法:
class="animation__placeholder" :class="[ `animation__placeholder--${animation}`, { 'animation__placeholder--top': alignment === 'top', 'animation__placeholder--center': alignment === 'center' || side === 'center', 'animation__placeholder--bottom': alignment === 'bottom', 'animation__placeholder--right': side === 'right', 'animation__placeholder--left': side === 'left', } ]"
注意:这里用模板字符串`animation__placeholder--${animation}`替代字符串拼接,比'xxx' + animation更直观。另外你原来的代码里有重复的animation__placeholder--center,这里合并成了一个条件alignment === 'center' || side === 'center',避免冲突。
方式2:使用计算属性(推荐,代码更清晰)
如果类名逻辑比较复杂,把所有类名的计算逻辑放到组件的计算属性里,可读性和维护性更好:
// 组件的computed选项 computed: { placeholderClasses() { const baseClasses = ['animation__placeholder'] // 添加动态拼接的类名 baseClasses.push(`animation__placeholder--${this.animation}`) // 添加条件类 if (this.alignment === 'top') baseClasses.push('animation__placeholder--top') if (this.alignment === 'center' || this.side === 'center') baseClasses.push('animation__placeholder--center') if (this.alignment === 'bottom') baseClasses.push('animation__placeholder--bottom') if (this.side === 'right') baseClasses.push('animation__placeholder--right') if (this.side === 'left') baseClasses.push('animation__placeholder--left') return baseClasses } }
然后在模板里直接绑定:
:class="placeholderClasses"
方式3:ES6计算属性名(纯对象语法实现)
如果你想继续用纯对象语法,可以用ES6的计算属性名,把动态键用方括号包裹,指定值为true(表示这个类始终生效):
class="animation__placeholder" :class="{ [`animation__placeholder--${animation}`]: true, 'animation__placeholder--top': alignment === 'top', 'animation__placeholder--center': alignment === 'center' || side === 'center', 'animation__placeholder--bottom': alignment === 'bottom', 'animation__placeholder--right': side === 'right', 'animation__placeholder--left': side === 'left', }"
内容的提问来源于stack exchange,提问作者Nathan S
相关产品推荐
相关产品推荐

