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