父组件通过传参控制子组件的样式

381 阅读1分钟

本功能的重点是利用vue的对象语法设置动态元素属性

参考:Class 与 Style 绑定 — Vue.js (vuejs.org)

1.通过属性绑定的形式,为 .my-search-container 盒子和 .my-search-box 盒子动态绑定 style 属性:

// 绑定元素的内联样式(这东西本质是JavaScript代码详细看上面官网代码)
<view class="my-search-container" :style="{'background-color': bgcolor}">
  <view class="my-search-box" :style="{'border-radius': radius + 'px'}">
    <uni-icons type="search" size="17"></uni-icons>
    <text class="placeholder">搜索</text>
  </view>
</view>

2.通过 props 定义 bgcolor 和 radius 两个属性,并指定值类型和属性默认值:

props: {
  // 背景颜色
  bgcolor: {
    type: String,
    default: '#C00000'
  },
  // 圆角尺寸
  radius: {
    type: Number,
    // 单位是 px
    default: 18
  }
}

3.移除对应 scss 样式中的 背景颜色 和 圆角尺寸

.my-search-container {
  // 移除背景颜色,改由 props 属性控制
  // background-color: #C00000;
  height: 50px;
  padding: 0 10px;
  display: flex;
  align-items: center;
}

.my-search-box {
  height: 36px;
  background-color: #ffffff;
  // 移除圆角尺寸,改由 props 属性控制
  // border-radius: 15px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .placeholder {
    font-size: 15px;
    margin-left: 5px;
  }
}

(本功能引用的黑马小程序源码)