iView‐Select - daniel-qa/Vue GitHub Wiki

#

  • 範例
<template>
  <div class="test-component" style="padding: 20px;">
    <h3>下拉選單測試</h3>
    
    <div class="select-wrapper" style="margin-top: 20px;">
      <h4>時間單位選擇</h4>
      <Select v-model="timeUnit" style="width: 80px;padding-left:5px;">
        <Option value="week">週</Option>
        <Option value="month">月</Option>
      </Select>
      
      <p style="margin-top: 20px;">選中的值: {{ timeUnit }}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TestComponent',
  data() {
    return {
      timeUnit: 'week'
    }
  }
}
</script>

<style scoped>
/* 覆蓋父組件的全局樣式 - 提高選擇器 specificity */
.select-wrapper ::v-deep .ivu-select-selection {
  background-color: #fff;
  width: auto;
  border-radius: 4px;
  height: 32px;
  border: 1px solid #dcdee2;
}

.select-wrapper ::v-deep .ivu-select-dropdown {
  background-color: #fff;
}

.select-wrapper ::v-deep .ivu-select-item {
  color: #515a6e;
  font-size: 14px;
}

.select-wrapper ::v-deep .ivu-select-item:hover {
  background-color: #f3f3f3;
}

.select-wrapper ::v-deep .ivu-select-item-focus {
  background-color: #f3f3f3;
}

.select-wrapper ::v-deep .ivu-select-selected-value {
  color: #515a6e;
  font-size: 14px;
}
</style>

  • 設定 dropdown 的寬度就會跟隨 Select 元件寬度的設定,兩者寬度一致。

只需在全局樣式把 width: 200px 改成 width: auto:

/deep/ .ivu-select-selection,
/deep/ .ivu-input {
  background-color: #021f554a !important;
  width: auto;        // ← 從 200px 改成 auto
  border-radius: 5px;
  height: 26px;
  line-height: 26px;
  margin-right: 10px;
  font-size: 14px;
  ...
}

這樣 dropdown 的寬度就會跟隨 Select 元件選項的寬度設定。


樣式汙染處理方式((由好到不得已)

  • 1 . 優先:用 scoped + ::v-deep(不加 !important)
<style scoped>
::v-deep .ivu-select-selection {
  background-color: #fff;
}
</style>
  • 2 . 次選:提高選擇器 specificity
::v-deep .my-wrapper .ivu-select-selection {
  background-color: #fff;
}
  • 3 . 不得已:才加 !important
::v-deep .ivu-select-selection {
  background-color: #fff !important;
}

!important 的缺點

難以維護,之後想再覆蓋更困難

表示樣式架構可能有問題

容易造成「!important 疊 !important」的惡性循環

  • 結論

你現在的情況(對抗 iView 內建樣式)加 !important 是可以接受的實務做法,但建議:

加上註解說明為什麼要用 !important

範圍盡量縮小,不要全局使用

父組件汙染問題

TestComponent 受到了父組件 schooliot.vue 的全局樣式污染:

/* schooliot.vue 中的全局樣式 */
/deep/ .ivu-select-selection {
  background-color: #021f554a !important;
  width: 200px;  /* 強制所有 Select 寬度為 200px */
  border-radius: 5px;
  height: 30px;
}

這些 /deep/ 樣式會穿透到所有子組件,導致:

❌ Select 寬度被強制設為 200px
❌ 背景色變成深藍色半透明
❌ 下拉選單背景色變成藍色
❌ 文字顏色變成白色

✅ 解決方案

在 TestComponent 中添加了更高優先級的樣式覆蓋:

::v-deep .ivu-select-selection ,還要加上 important

::v-deep .ivu-select-selection {
  background-color: #fff !important;
  width: auto !important;  /* 恢復自動寬度 */
  border-radius: 4px !important;
  height: 32px !important;
  border: 1px solid #dcdee2 !important;
}

現在 TestComponent 中的 Select 會顯示為:

✅ 白色背景
✅ 寬度由 style="width: 100px" 控制
✅ 標準的 iView 樣式
✅ 不受父組件污染

重新載入頁面,現在應該能看到正常的 Select 樣式了!

⚠️ **GitHub.com Fallback** ⚠️