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

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

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

翻译好的代码如下:

with ```reactive```
```js
type BookForm = {
    name: string;
    author: string;
    totalPages: number;
    read: boolean;
}

const form = reactive<BookForm>({
    name: '',
    author: '',
    totalPages: 0,
    read: false,
});

or, you can break it out into separate refs

const name = ref(''); // types are automatically inferred
const author = ref('');
const totalPages = ref(0);
const read = ref(false);

you can explicitly set type for refs too

const book = ref<Book>(); // book will have a type of Book | undefined

<details>
<summary>英文:</summary>

with ```reactive```
```js
type BookForm = {
    name: string;
    author: string;
    totalPages: number;
    read: boolean;
}

const form = reactive&lt;BookForm&gt;({
    name: &#39;&#39;,
    author: &#39;&#39;,
    totalPages: 0,
    read: false,
});

or, you can break it out into separate refs

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

you can explicitly set type for refs too

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:

确定