JavaScript/typescript/回调函数:修订间差异
来自康健生活
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
在每个页面的 <code>methods</code> (VUE.js) 对象中,我需要定义一个在走后端接口之前,校验一下登录状态的功能,代码如下: | |||
<syntaxhighlight lang="javascript"> | |||
import {whetherNoLogin} from '@@/plugins/util.ts'; | |||
/* 判断用户是否登录 */ | |||
if(whetherNoLogin(this.$store.state.user, this.$message)){ | |||
return false | |||
}</syntaxhighlight> | |||
函数定义如下: | |||
{{hc|head=@@/plugins/util.ts|output=<syntaxhighlight lang="typescript"> | |||
/** | |||
* 验证登陆状态 | |||
* @param user | |||
* @param $message | |||
*/ | |||
export function whetherNoLogin(user:{token: string|undefined|null}, $message: (arg:object) => void): boolean{ | |||
if(user && user.token){ | |||
return false | |||
}else{ | |||
$message({ | |||
message: '请先登录', | |||
type: 'warning', | |||
duration: '2000' | |||
}); | |||
return true | |||
} | |||
} | |||
</syntaxhighlight>}} | |||
其中回到函数如果使用内联,则 <code>(arg:object) => void)</code> | |||
== 类型 == | == 类型 == | ||
声明回调函数类型: | 声明回调函数类型: | ||