条件判断
我们经常需要根据不同的状态呈现不同的界面,比如有的用户是vip要显示vip的Logo。Omi有许多种方式满足你的要求。
方式一
class ConditionTest extends Omi.Component {
constructor(data) {
super(data);
}
render () {
return `
<div o-if="isVip">you are VIP.</div>
<div o-if="!isVip">you are not VIP.</div>
`;
}
}
当然也可以利用{{expression}}:
class ConditionTest extends Omi.Component {
constructor(data) {
super(data);
}
render () {
return `
<div>you are {{isVip?'':'not'}} VIP.</div>
`;
}
}
类似于 JavaScript 表达式,Omi 表达式可以包含字母,操作符,变量,以上的omi.js的条件判断方式。
方式二
class ConditionTest extends Omi.Component {
constructor(data) {
super(data);
}
render () {
if(this.data.isVip){
return '<div>you are VIP.</div>';
}else{
return '<div>you are not VIP.</div>';
}
}
}
render就是提供了很好的可编程性,里面可以写任意js逻辑代码。对了,差点忘了,style方法里面也可以写js逻辑的。
class ConditionTest extends Omi.Component {
constructor(data) {
super(data);
}
style (){
if(this.data.isVip){
return 'div{ color : red; }';
}else{
return 'div{ color : green; }';
}
}
render () {
if(this.data.isVip){
return '<div>you are VIP.</div>';
}else{
return '<div>you are not VIP.</div>';
}
}
}
这里需要特别注意,如果同一个组件使用了多次,只会使用第一次生成的局部CSS。如果需要每次都生成不同的局部CSS,需要创建或者声明的时候标记scopedSelfCSS。即:
<your-component scopedSelfCSS></your-component>
也支持下面的简写形式:
<your-component ssc></your-component>
如果是javascript创建的时候:
new YourComponent({ }, { scopedSelfCSS : true })
方式三
class ConditionTest extends Omi.Component {
constructor(data) {
super(data);
}
render() {
return `
${this.data.isVip
?"<div>you are VIP.</div>"
:"<div>you are not VIP.</div>"
}
`;
}
}
当然可以使用${ }里面写javascript代码进行输出。
方式四
如果你使用的是omi.mustache.js,你可以使用下面的方式:
class ConditionTest extends Omi.Component {
constructor(data) {
super(data);
}
render () {
return `{{#isVip}}
<div>you are VIP.</div>
{{/isVip}}
{{^isVip}}
<div>you are not VIP.</div>
{{/isVip}}`;
}
}
完全使用mustachejs的条件判断的语法。当然Omi不强制你使用mustachejs。你可以是omi.lite.js,然后重写Omi.template方法去使用任意你喜爱的模板引擎。