如何让样式道具作用于 VueJs 中的特定元素

问题描述 投票:0回答:1

我正在创建一个按钮,它需要有多种状态(悬停、聚焦、按下和禁用)。

我还需要我的默认按钮具有默认尺寸(大)和较小的尺寸(小)。我试图通过 vue props 将不同的属性传递到我的按钮上,但它们都不起作用。

目前我只是想在按钮上获取一些基本的尺寸属性(获取高度和宽度),但它们正在工作,我不知道为什么,因为我没有收到任何错误。

下面是

<template>
中的按钮:

<button
      class="primaryButton"
      :class="[
        size + 'large',
        type + 'primary',

        {
          'default-state': !isActive,
          hover: isActive && isHovered,
          focused: isActive && isFocused,
          pressed: isActive && isPressed,
          disabled: isDisabled
        }
      ]"
      @mouseenter="isHovered = true"
      @mouseleave="isHovered = false"
      @focus="isFocused = true"
      @mousedown="isPressed = true"
      @mouseup="isPressed = false"
      @click="handleClick"
      :disabled="isDisabled"
    >
      <slot />
</button>

以下是

<script>

export default {
  props: {
    size: {
      default: 'large',
      small: 'small'
      //default size
    },
    type: {
      default: 'default',
      focused: 'focused',
      pressed: 'pressed',
      disAbled: 'disAbled'
      //default type
    }
  },
  data() {
    return {
      isActive: true,
      isHovered: false,
      isFocused: false,
      isPressed: false,
      isDisabled: false
    }
  },
  methods: {
    handleClick() {
      if (!this.isDisabled) {
        this.buttonClick
      }
    }
  }
}

以下是

<style>

.primaryButton {
  background-color: #a5042a;
  border: none;
  color: white;
  border-radius: 5px;

}
.primaryButton:hover {
  background-color: #ed063d;
  cursor: pointer;
}

.large-size {
  min-height: 45px;
  min-width: 130px;
}
html css vue.js vue-component
1个回答
0
投票

您可以利用 Vue 中的slots。您可以拥有一个组件

BaseButton.vue
,您可以向其传递 props 或 fallthrough 属性,以便按钮具有不同的样式。这是 Vue Playground 上的一个小演示。这是
BaseButton.vue

的示例

<template>
  <button class="default">
    <slot></slot>
  </button>
</template>

<style scoped>
.default {
    width: 100px;
    height: 30px;
    background-color: blue;
    color: white;
    border: none;
    transition: all .2s;
}

.default:hover {
    background-color: aliceblue;
}

.large {
    width: 200px;
    height: 50px;
    background-color: red;
}

.large:hover {
    /* specific hover styles */
}

.small {
    width: 75px;
    height: 10px;
}
</style>

© www.soinside.com 2019 - 2024. All rights reserved.