一、先分清楚:你说的 complete 应该是 computed(计算属性)

vue 里没有 complete,是 computed 计算属性themeColor() 写在 computed 里,分两种场景使用:模板使用、js逻辑里使用。

1. 基础写法示例

export default {
  computed: {
    themeColor() {
      // 这里写逻辑,return 最终颜色值
      return '#ff4400'
    }
  }
}

2. 在 template 模板中使用(最常用)

方式1:行内样式 style

<!-- 文字颜色 -->
<view :style="{ color: themeColor }">主题文字</view>

<!-- 背景色 -->
<view :style="{ background: themeColor }">背景</view>

<!-- 边框 -->
<view :style="{ borderColor: themeColor }"></view>

方式2:class 配合 css 变量(uniapp/vue 推荐)

模板:

<view class="box" :style="{'--color': themeColor}"></view>

css:

.box {
  color: var(--color);
  border: 1px solid var(--color);
}

方式3:组件属性传值

<button :color="themeColor">按钮</button>

3. 在 script js 逻辑里使用(methods/生命周期)

直接 this.themeColor 调用,不需要加括号()

methods: {
  test() {
    console.log(this.themeColor)
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.themeColor
    })
  }
},
onReady() {
  console.log(this.themeColor)
}

二、带参数的 computed 特殊情况

如果你 computed 是这种传参写法(返回函数):

computed: {
  themeColor() {
    // 返回函数,可传参
    return (opacity) => {
      return `rgba(255,68,0,${opacity})`
    }
  }
}

使用方式

模板:

<view :style="{color: themeColor(0.8)}"></view>

js内:

let color = this.themeColor(0.5)

三、结合你上面轮播图组件实战示例

<template>
  <swiper :indicator-active-color="themeColor">
    ...
  </swiper>
</template>
<script>
export default {
  props: ['itemData'],
  computed: {
    themeColor() {
      // 从后端配置拿主题色
      return this.itemData.style.btnColor || '#fff'
    }
  }
}
</script>

重点总结

  1. 普通无参 computed:模板 themeColor,js this.themeColor不加括号
  2. 若 computed 返回函数(需要传参):模板 themeColor(参数),js this.themeColor(参数)
  3. computed 自带缓存,依赖值变化才会重新计算,比写在 methods 性能更好

更多推荐