在vue中,我有一个服务类[用于做axios类],以前是用javascript编写的。现在代码库正在迁移到完整的打字稿。...此模块必须迁移到打字稿 下面如何成为一个好的打字代码?
import Axios from 'axios'
export default {
createStudent (name, age) {
return Axios.post('localhost:9090/student', { name: name , age: age })
}
}
我知道我可以将扩展名更改为ts并且可以正常工作...但是想要在打字稿中使用正确的代码 应该上课吗?该代码是从vue类组件中调用的,它将axios调用抽象到一个地方,而不是污染vue组件类。 如果我将其作为打字稿类,那么如何在基于vue类的组件中使用它?我应该注入还是仅创建新的?
答案 0 :(得分:1)
此代码是有效的TypeScript,因为TypeScript是JavaScript的超集,但它也提供了类型。
由于没有使用.each()
类实例,因此它目前无法从类中受益,这是JavaScript和TypeScript中的反模式。
最好不要使用$("p").each(function() {
console.log($(this).html())
});
的方法转换为静态方法,但是纯静态类也是一种反模式:
Dim script = "var returnValue = function(){ var value; value=10-2; return value; }"
Dim task As Threading.Tasks.Task = browser.EvaluateScriptAsync(script)
Dim taskResult As String
task.ContinueWith(Sub(t)
If t.IsFaulted = False Then
Dim response = t.Result 'Error: Result is not a member of Task'
If response.Success And response.Result IsNot Nothing Then
taskResult = response.Result
End If
End If
End Sub)
MsgBox(taskResult)
它可以是带有要实例化的原型方法的类:
browser.EvaluateScriptAsync(script).ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
var onePlusOne = (int)response.Result;
//Do something here (To interact with the UI you must call BeginInvoke)
}
});
由于类也充当接口,因此存在此类的一个很好的理由是在需要时将其用作类型:
this
该类应该用作单例:
this
或在每次使用时实例化:
export default class Service {
static createStudent (name, age) {...}
}
类不应用作美化的命名空间,这是模块的用途。由于它已经是一个模块,因此可以是:
export class Service {
createStudent (name, age) {...}
}
它可以被命名空间,并受益于成为一个ES模块,例如使用摇树:
let service: Service = { createStudent() { ... } }; // not an instance of Service class