创建新的 Vue 3 项目:

按装vue3的 工具

npm install -g @vue/cli

创建一个新的 Vue 3 项目:

vue create vue3-todolist

进入项目目录:

cd vue3-todolist

代码:

在项目的 src/components 目录下,创建一个新的文件 TodoList.vue,将以下代码复制到这个文件中:

<template>
  <div>
    <h1>任务 例表</h1>

    <div>
      <input v-model="newTodo" @keyup.enter="addTodo" placeholder="增加任务">
      <button @click="addTodo">Add</button>
    </div>

    <ul>
      <li v-for="(todo, index) in todos" :key="index">
        <span>{{ todo.text }}</span>
        <button @click="removeTodo(index)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script>
import { ref } from 'vue';

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

    const addTodo = () => {
      if (newTodo.value.trim() !== '') {
        todos.value.push({ text: newTodo.value });
        newTodo.value = '';
      }
    };

    const removeTodo = (index) => {
      todos.value.splice(index, 1);
    };

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

在主应用文件中使用组件:

打开 src/App.vue 文件,将以下代码替换到文件中:

<template>
  <div id="app">
    <TodoList />
  </div>
</template>

<script>
import TodoList from './components/TodoList.vue';

export default {
  components: {
    TodoList
  }
};
</script>

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

button {
  margin-left: 5px;
}
</style>

运行项目:

在终端中运行以下命令:

npm install
npm run serve

效果:

vue3开发一个todo List-LMLPHP

12-25 21:32