使用TypeScript在一个简单的Vue 3表单中

huangapple go评论92阅读模式
英文:

Using TypeScript on a simple vue 3 form

问题

我在我的Vue 3组合API项目中如何使用TypeScript一直感到非常困惑。我已经查看了一些教程,甚至正在一个使用TypeScript的项目中,但似乎对我来说还不太明白,不知道为什么。我认为创建一个使用Vue 3组合API的应用程序,并得到Stack Overflow社区的帮助会对我有所帮助。

我有一个简单的应用程序,用来跟踪我已经阅读或计划阅读的书籍。以下是一些字段:

  1. 书名
  2. 作者名
  3. 总页数
  4. 阅读完成情况

请问有人能帮助我理解如何在这个表单中使用TypeScript吗?这对你来说可能很基础,但我只是想弄清楚。随着我构建我的书籍跟踪器,我会提出更多问题。

这是我的存储库,感谢您能提供的任何帮助。

英文:

I am having the hardest time understanding how to use TypeScript in my Vue 3 composition api project. I have looked at tutorials and I'm even on a project using it but something is not clicking for me and I'm not sure why. I think what would help me is to create my own vue 3 composition api app with the stack overflow communities help.

I have a simple application to track books that I read or plan to read. Here are just a few fields:

  1. Name of Book
  2. Name of Author
  3. Total Pages
  4. Read Completed

Can someone please help me to understand how I would use TypeScript with this form? This may seem very basic for you but I'm just trying to understand. I will ask more questions as I build out my book tracker.

Here's my repo
Thanks for any help you can provide.

答案1

得分: 0

翻译好的代码如下:

  1. with ```reactive```
  2. ```js
  3. type BookForm = {
  4. name: string;
  5. author: string;
  6. totalPages: number;
  7. read: boolean;
  8. }
  9. const form = reactive<BookForm>({
  10. name: '',
  11. author: '',
  12. totalPages: 0,
  13. read: false,
  14. });

or, you can break it out into separate refs

  1. const name = ref(''); // types are automatically inferred
  2. const author = ref('');
  3. const totalPages = ref(0);
  4. const read = ref(false);

you can explicitly set type for refs too

  1. const book = ref<Book>(); // book will have a type of Book | undefined
  1. <details>
  2. <summary>英文:</summary>
  3. with ```reactive```
  4. ```js
  5. type BookForm = {
  6. name: string;
  7. author: string;
  8. totalPages: number;
  9. read: boolean;
  10. }
  11. const form = reactive&lt;BookForm&gt;({
  12. name: &#39;&#39;,
  13. author: &#39;&#39;,
  14. totalPages: 0,
  15. read: false,
  16. });

or, you can break it out into separate refs

  1. const name = ref(&#39;&#39;); // types are automatically inferred
  2. const author = ref(&#39;&#39;);
  3. const totalPages = ref(0);
  4. const read = ref(false);

you can explicitly set type for refs too

  1. const book = ref&lt;Book&gt;(); // book will have a type of Book | undefined

huangapple
  • 本文由 发表于 2023年2月7日 02:37:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定