通过Mixin,我们可以在标签之间共享通用功能。Mixin可以是函数,类或对象。考虑每个标签应使用的身份验证服务的情况。
- 定义Mixin-在调用mount()之前使用riot.mixin()方法定义mixin。
riot.mixin('authService', {
init: function() {
console.log('AuthService Created!')
},
login: function(user, password) {
if(user == "admin" && password == "admin"){
return 'User is authentic!'
}else{
return 'Authentication failed!'
}
}
});- 初始化mixin-在每个标签中初始化mixin。
this.mixin('authService') - 使用mixin-初始化后,可以在标记内使用mixin。
this.message = this.login("admin","admin"); 例子
以下是完整的示例。
custom8Tag.tag
<custom8Tag>
<h1>{ message }</h1>
<script>
this.mixin('authService')
this.message = this.login("admin","admin")
</script>
</custom8Tag>custom9Tag.tag
<custom9Tag>
<h1>{ message }</h1>
<script>
this.mixin('authService')
this.message = this.login("admin1","admin")
</script>
</custom9Tag>custom8.htm
<html>
<head>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/riot/3.13.2/riot+compiler.min.js"></script>
</head>
<body>
<custom8Tag></custom8Tag>
<custom9Tag></custom9Tag>
<script src = "custom8Tag.tag" type = "riot/tag"></script>
<script src = "custom9Tag.tag" type = "riot/tag"></script>
<script>
riot.mixin('authService', {
init: function() {
console.log('AuthService Created!')
},
login: function(user, password) {
if(user == "admin" && password == "admin"){
return 'User is authentic!'
}else{
return 'Authentication failed!'
}
}
});
riot.mount("*");
</script>
</body>
</html>预览后,效果:
User is authentic!
Authentication failed!作者:terry,如若转载,请注明出处:https://www.web176.com/riotjs/2185.html
支付宝
微信