【发布时间】:2020-11-17 16:38:05
【问题描述】:
我正在尝试通过计算的 switch case 将一个类从父组件绑定到子组件到插槽。 家长:
<template>
<mcTooltip :elementType="'text'"><p>Test</p></mcTooltip>
</template>
<script>
import mcTooltip from '@/components/mcTooltip/index.vue';
export default {
components: {
mcTooltip
}
};
</script>
孩子:
<template>
<div>
<slot :class="[elementClass]" />
</div>
</template>
<script>
export default {
props: {
elementType: {
type: String,
required: true,
// must have one of these elements
validator: (value) => {
return ['text', 'icon', 'button'].includes(value);
}
}
},
data() {
return {};
},
computed: {
elementClass: () => {
// return this.elementType ? 'tooltip--text' : 'tooltip--text';
// calls prop value for verification
switch (this.elementType) {
case 'text':
return 'tooltip--text';
case 'icon':
return 'tooltip--icon';
case 'button':
return 'tooltip--button';
default:
return 'tooltip--text';
}
}
},
};
</script>
<style lang="scss" scoped>
.tooltip--text {
text-decoration: underline dotted;
cursor: pointer;
&:hover {
background: $gray_220;
}
}
</style>
无论我尝试什么,我似乎都无法让它发挥作用。那是我最近的尝试。 vue devtools 对我的计算道具说“(评估期间的错误)”。
【问题讨论】:
-
试试不带箭头函数的计算属性。您还可以将开关替换为对象 -
{text: 'tooltip--text', icon: 'tooltip--icon', button: 'tooltip--button'}[this.elementType] || 'tooltip--text' -
您通常不能在
<slot>元素上设置类(或任何其他属性)。见Bind class to a slot in Vue.js 2
标签: vue.js vue-component computed-properties