RIOT.JS教程:Mixin

通过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

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年3月31日 下午3:33
下一篇 2021年3月31日 下午3:42

相关推荐

发表回复

登录后才能评论