【问题标题】:Vue dynamic class binding with computed propsVue 动态类绑定与计算道具
【发布时间】: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'
  • 您通常不能在&lt;slot&gt; 元素上设置类(或任何其他属性)。见Bind class to a slot in Vue.js 2

标签: vue.js vue-component computed-properties


【解决方案1】:

我找到了解决办法,我的做法如下:

  <div
    v-show="showTooltip"
    ref="mcTooltipChild"
    :class="['tooltip__' + elementType]"
  ></div>

    elementType: {
      type: String,
      default: 'small',
    },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2023-02-17
    • 2020-10-24
    • 1970-01-01
    • 2017-07-31
    • 2020-05-09
    相关资源
    最近更新 更多