返回

Vue 项目实战(二):Vue3 + Vite + TypeScript 实现 ToDoList 刷题打卡

前端

前言

在上一篇文章中,我们介绍了 Vue3 的基本概念和搭建了 Vue3 的环境。本篇文章,我们将通过一个 TodoList 项目来进一步学习 Vue3 的使用。

搭建项目

首先,我们需要创建一个新的 Vue3 项目。可以使用 Vue CLI 来快速创建项目。

vue create todolist

选择好项目名称和包管理器后,项目就会被创建出来。

安装依赖

接下来,我们需要安装一些必要的依赖。

npm install -D vite @vitejs/plugin-vue typescript
  • vite:一个现代的构建工具,可以快速构建和开发 Vue 项目。
  • @vitejs/plugin-vue:Vite 的 Vue 插件,用于支持 Vue 项目。
  • typescript:一种流行的 JavaScript 超集语言,可以用来编写 Vue 组件。

配置项目

package.json 文件中,我们需要添加以下配置:

{
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "vue": "^3.0.0",
    "vite": "^2.0.0",
    "@vitejs/plugin-vue": "^1.0.0",
    "typescript": "^4.0.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.0.0",
    "typescript": "^4.0.0"
  }
}

创建组件

接下来,我们需要创建一些组件。首先,创建一个 App.vue 文件。

<template>
  <div id="app">
    <h1>Todo List</h1>
    <ul>
      <li v-for="todo in todos" :key="todo.id">
        {{ todo.text }}
      </li>
    </ul>
    <input type="text" v-model="newTodo" @keyup.enter="addTodo">
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const todos = ref([])
    const newTodo = ref('')

    const addTodo = () => {
      if (newTodo.value !== '') {
        todos.value.push({
          id: Date.now(),
          text: newTodo.value
        })
        newTodo.value = ''
      }
    }

    return {
      todos,
      newTodo,
      addTodo
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

ul {
  list-style-type: none;
  display: flex;
  justify-content: center;
  padding: 0;
}

li {
  margin: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

input {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  width: 300px;
}
</style>

这个组件包含了一个简单的待办事项列表。它有一个 todos 数组,用于存储待办事项。还有一个 newTodo 变量,用于存储新的待办事项。当用户在输入框中输入待办事项并按回车键时,addTodo() 函数将被调用,并将新的待办事项添加到 todos 数组中。

运行项目

现在,我们可以运行项目了。

npm run dev

项目将在 http://localhost:3000 上运行。

总结

本篇文章中,我们介绍了如何使用 Vue3、Vite 和 TypeScript 来构建一个 TodoList 项目。我们学习了如何创建 Vue 组件、如何使用 Vuex 来管理数据,以及如何使用 TypeScript 来编写 Vue 组件。希望本篇文章对您有所帮助。