使用render函数实现一个组件在不同环境的不同样式

背景: 一个项目对接多个渠道,需求要求的是根据不同的渠道显示不同的样式(例如颜色,文案),由于只上线一套代码,所以在开发时,对于不同渠道我们必须整合样式的显示。
对于一个按钮根据不同的渠道显示不同的颜色,我们可以这样做

<template>
  <div>
    <div v-if="channel == 'a'">
      <button class="channela">Channel-a</button>
    </div>
    <div v-else-if="channel == 'b'">
      <button class="channelb">Channel-b</button>
    </div>
    <div v-else>
      <button class="channelc">Channel-c</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "bussines",
  data() {
    return {};
  },
  props: {
    channel: {
      type: String,
      default: "a"
    }
  }
};
</script>
<style scoped>
.btn {
  display: block;
  line-height: 1.2rem;
  margin: 0.3rem 0.2rem;
  text-align: center;
  border-radius: 0.1rem;
  border: 0;
}
.channela {
  background: #3db3f9;
}
.channelb {
  background: #b6b6b6;
}
.channelc {
  background: #fff;
}
</style>

但是这样写让代码看着冗杂,再多几个渠道你便需要再加几个v-else-if,这个时候render函数便有了用武之地
用render函数可以这样写
创建一个组件test.vue


<script>
export default {
  name: "bussines",
  data() {
    return {};
  },
  props: {
    channel: {
      type: String,
      default: "a"
    },
    content: { type: String, default: "提交" }
  },
  render(h) {
    return h("button", {
      class: {
        btn: true,
        "channel-a": this.channel == "a",
        "channel-a": this.channel == "b",
        "channel-c": this.channel == "c"
      },
      domProps: {
        innerText: this.content
      },
      on: {
        click: this.clickFun
      }
    });
  },
  methods: {
    clickFun() {
      //按钮点击后触发的方法
    }
  }
};
</script>
<style scoped>
.btn {
  display: block;
  line-height: 1.2rem;
  margin: 0.3rem 0.2rem;
  text-align: center;
  border-radius: 0.1rem;
  border: 0;
}
.channel-a {
  background: #3db3f9;
}
.channel-b {
  background: #b6b6b6;
}
.channel-c {
  background: #fff;
}
</style>

最后用import引用该组件

<template>
  <div>
    <test channel="b" content="获取"></test>
  </div>
</template>

<script>
import test from "./components/test.vue";
export default {
  name: 'login',
  data(){
    return{
    }
  },
  components:{
      test 
  }
}
</script>

channel属性为渠道号,content为按钮文案,根据不同渠道显示不同颜色,不同文案。这样无论加多少,我们都只需要在组件里加上相应的样式,修改channel,content的值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值