4.改進 button 組件的樣式-1

1.CSS 內聯樣式和內部樣式

內聯樣式

<button style="color:red">click me</button>

內部樣式

<!DOCTYPE html>
<html>
<head>
  <style>
    .redblue-button {
      color: red;
    }
  </style>
</head>
<body>
  <button class="my-button">click me</button>
</body>
</html>

# 知識點:

  • css由兩部分組成,選擇器 {屬性:屬性值;屬性:屬性值}
  • 屬性值爲若干單詞,要給其加引號
  • html 標籤屬性值可以加引號也可以不加,一般考慮瀏覽器兼容性應加引號

可見 css 通過給元素添加 style 或 class 屬性可以設定元素的樣式

我們依然可以在使用 my-button 組件時添加 style 屬性,在 App.vue 文件如下使用 my-button

<my-button style="color:red">click me</my-button>

這個樣式覆蓋了之前組件的樣式

但是如果我們需要 my-button 直接支持 color 屬性呢?我們希望如下的寫法可以修改 my-button 的樣式。

<my-button color="red">click me</my-button>

2. Vue 綁定內聯樣式

Prop 可以在組件上註冊一些自定義的 attribute。

我們在 my-button.vue 默認導出中添加 prop

<script>
export default {
  name: 'my-button',
  props:['color']
}
</script>

現在 my-button 元素有了 color 屬性,但它並不能改變元素的顏色

要改變顏色,我們還需要綁定 Style 類似於 CSS 內聯樣式,不過需要傳入的是 js 的對象或數組

<template>
  <button :style="{color}">
    <slot></slot>
  </button>
</template>

現在傳入的 color 值可以改變元素的顏色

# 知識點:

  • v-bind:style 綁定內聯樣式,其可以簡寫爲:style
  • ES6語法允許對象屬性直接寫入變量,變量名即屬性名, 變量的值即屬性值

3. Vue 綁定內部樣式

我們將前面的CSS內部樣式放入 my-button.vue 組件文件中

<style>
  .red-button {
    color: red;
  }
</style>

並在 App.vue my-button 元素中應用 class

<my-button class="red-button">click me</button>

 但是如果我們預先自定義了多個樣式

<style>
  .red-button {
    color: red;
  }

  .yellow-button {
    color: yellow;
  }

  .blue-button {
    color: blue;
  }
</style>

並且依然想採用如下的方式應用CSS樣式

<my-button color="red">click me</my-button>

我們刪掉了之前綁定的 style屬性,現在需要綁定 class 屬性

如果沒有給 color 屬性賦值則 class 爲 null 即爲默認的樣式

如果給 color 賦值了,則 color 的值加上 '-button' 即爲該元素的 class 

<template>
  <button :class="color ? color + '-button' : ''">
    <slot></slot>
  </button>
</template>

 

# 知識點:

  • v-bind:class 綁定內部樣式,其可以簡寫爲:class。
  • 三元運算符 條件表達式 ?表達式1 : 表達式2 。條件表達式爲真時調用表達式1,否則表達式2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章