我有一个模仿div行为的vuejs功能组件。为此,我根据收到的道具设置它的类。
类似这样的东西:
<MyDiv textAlign="left">Div with left aligned text</MyDiv>
成为:
<div class="text-left">Div with left aligned text</div>
但是,如果MyDiv组件是其他某个组件的根元素,例如:
Card.vue
<template>
<MyDiv display="inline-block" textAlign="center">
<slot />
</MyDiv>
</template>
并且如果Card在使用时收到任何类属性,我将无法基于MyDiv道具设置类属性值,相反,类(在MyDiv上)将被Card接收的类所覆盖。
所以这个:
<Card class="cool-style">Card content</Card>
成为:
<div class="cool-style">Card content</div>
不要这样(我需要):
<div class="cool-style inline-block text-center">Card content</div>
这里是MyDiv组件:
MyDiv.vue
export default {
name: 'my-div',
functional: true,
props: {
textAlign: {
type: String,
allowed: ['left', 'right', 'center'],
default: null
},
display: {
type: String,
allowed: ['hidden', 'block', 'inline-block', 'flex'],
default: null
}
},
render: function(createElement, context) {
let classes = [];
// Adds parent class to itself
if (typeof context.data.staticClass == 'string') {
classes.push(context.data.staticClass);
}
let classes = classes.concat([
'my-div',
context.props.textAlign && `text-${context.props.textAlign}`,
context.props.display && context.props.display
]);
classes = classes.filter(elm => elm != null);
classes = classes.join(' ').trim();
return createElement(
props.type,
{
attrs: {
class: classes
}
},
context.children
);
}
};
TL; DR
当我的自定义类的父级已经设置了一个类时,如何将我的自定义类强制为vue功能组件?
附带说明,可以使用statefull(非功能和常规)组件来完成。
替换