YOUR FIRST METEOR APPLICATION翻译(九)——账号(accounts)

账号
好吧,这章顾名思义就是怎么在Meteor.js里面实现账号登陆和注册的功能,只要在HTML模板里面输入以下代码,就可以实现了~

1
{{> loginButtons}}

没错,你没有听错,就是这么简单,我们这章就讲完了~

当然,这是有包依赖的报的,只要在项目目录里面使用终端运行以下命令装上以下两个依赖就好~

1
2
meteor add accounts-password
meteor add accounts-ui

当然,我也不是这么不负责的人,当然还会为大家送上点干货的~

既然有了登陆,那我们肯定需要对登陆状态进行一个判定,下面的代码就是为这个功能而生的:

1
2
3
4
5
6
7
<template name="addPlayerForm">
{{#if currentUser}}
<form>
<input type="text" name="playerName"> <input type="submit" value="Add Player">
</form>
{{/if}}
</template>

如果登陆成功了,模板里面就会显示一个文本框和按钮了。

当我们登陆了以后我们又会想识别当前的用户来实现更多的功能,下面的代码就会帮助你:

1
2
3
4
5
6
7
var currentUserId = Meteor.userId();
'submit form': function(event){
event.preventDefault();
var playerNameVar = event.target.playerName.value;
var currentUserId = Meteor.userId();
PlayersList.insert({name: playerNameVar, score: 0 });
}

其实,Meteor.userId()就是返回当前用户的id的,所以获取了id之后我们就可以做我们想做的事了。

感谢meteortips & David以上内容根据英文版的YOUR FIRST METEOR APPLICATION粗略翻译而来,在未经我本人允许的情况下请勿转载,违者本人保留法律追究的权利。