Vue3 重构待办事项(主要练习组件化)

Vue3 重构待办事项(主要练习组件化)

  • [1. 前情回归](#1. 前情回归)
  • [2. 重构步骤](#2. 重构步骤)
  • [3. 完整项目结构和代码](#3. 完整项目结构和代码)

1. 前情回归

在之前的《Vue3 基础实战练习》一章中,我们利用待办事项需求,将Vue3 的基础知识(包括模板语法、响应式基础、类与样式绑定、条件渲染、列表渲染、事件处理、表单输入绑定、侦听器)做了一次应用复习。

在本次练习中,我们希望通过通过组件化的思想,对页面进行拆分和重构

2. 重构步骤

(1)创建组件。

从页面上来看很清晰可以分为三个部分,头部、列表和底部。因此,我们需要重新创建3个组件,分别名为 Header.vue、List.vue、Footer.vue。并且将对应的 template、script、css 剪切到对应的文件中。

(2)引入和使用组件。

在 App.vue 中引入并使用 Header.vue、List.vue、Footer.vue 3个组件。但是此时还不能使用,因为父组件和子组件的数据和事件并未进行通信。

(3)父组件和子组件的数据通信。

使用defineModel() 在子组件定义需要双向绑定的父组件数据,并且在父组件那使用类似 <Header v-model:todos="todos"/> 的方式进行绑定。

(4)父组件和子组件的事件通信。

因为 Footer 组件的 removeAllCompleted 事件,牵扯到 filters,而 filters 有关系到 List 组件中的待办事项展示。

javascript 复制代码
const filters = {
  all: (todos) => todos,
  active: (todos) => todos.filter(todo => !todo.completed),
  completed: (todos) => todos.filter(todo => todo.completed)
}

const filteredTodos = computed(() => filters[visibility.value](todos.value))

function removeAllCompleted() {
  if (window.confirm('确定要删除所有已完成的待办事项吗?')) {
    todos.value = filters.active(todos.value)
  }
}

因此,为了简化代码,我们可以 defineEmits 将事件发射出去,在 App.vue 中进行处理。

(5)重复的样式代码,我们可以创建一个 common.css 放入,并且通过 import 方式导入到各个组件中。

3. 完整项目结构和代码

App.vue:

javascript 复制代码
<template>
  <!-- 最外层容器 -->
  <section class="todoapp">
    <!-- 头部 -->
    <Header v-model:todos="todos"/>
    <!-- 待办列表 -->
    <List v-model:todos="todos" v-model:filteredTodos="filteredTodos"/>
    <!-- 底部 -->
    <Footer v-model:todos="todos" v-model:remaining="remaining" v-model:visibility="visibility" @removeAll="removeAllCompleted"/>
  </section>
</template>

<script setup>
import { ref, computed, watchEffect } from 'vue';
import Header from '@/components/Header.vue';
import List from '@/components/List.vue';
import Footer from '@/components/Footer.vue';

const STORAGE_KEY = 'todo-list'
// 从本地存储中获取待办事项列表,没有就使用空数组初始化(第一次)
const todos = ref(JSON.parse(localStorage.getItem(STORAGE_KEY)) || []);
const visibility = ref('all') // 默认显示所有待办事项

const filters = {
  all: (todos) => todos,
  active: (todos) => todos.filter(todo => !todo.completed),
  completed: (todos) => todos.filter(todo => todo.completed)
}

// 根据当前状态显示对应的待办事项
const filteredTodos = computed(() => filters[visibility.value](todos.value))
const remaining = computed(() => filters.active(todos.value).length)

// 添加侦听器
watchEffect(() => {
  // 每次待办事项列表变化时,更新本地存储
  // 因为todos.value是响应式的,所以这里不需要手动触发更新
  localStorage.setItem(STORAGE_KEY, JSON.stringify(todos.value))
})

// 监听 hash 变化
window.addEventListener('hashchange', onHashChange)

function onHashChange() {
  const route = window.location.hash.replace(/#\/?/, '')
  console.log('route', route)
  if (filters[route]) {
    visibility.value = route
  } else {
    window.location.hash = ''
    visibility.value = 'all'
  }
}

// 删除所有已完成
function removeAllCompleted() {
  if (window.confirm('确定要删除所有已完成的待办事项吗?')) {
    todos.value = filters.active(todos.value)
  }
}

</script>

<style lang="scss" scoped>
@import './assets/todo.css';
.todoapp {
  background: #fff;
  margin: 130px auto;
  position: relative;
  box-shadow:
    0 2px 4px 0 rgba(0, 0, 0, 0.2),
    0 25px 50px 0 rgba(0, 0, 0, 0.1);
  width: 800px;
}

</style>

Header.vue:

javascript 复制代码
<template>
  <header class="header">
    <h1>待办事项</h1>
    <input type="text" class="new-todo" placeholder="添加新的待办事项" @keyup.ctrl.enter="addTodo" />
  </header>
</template>

<script setup>
const todos = defineModel('todos')

// 添加待办事项
function addTodo(event) {
  const value = event.target.value.trim()
  if (value) {
    todos.value.push({
      id: Date.now(),
      title: value,
      completed: false
    })
    event.target.value = '' // 清空输入框
    // console.log('todos', todos.value)
    // console.log('filteredTodos', filteredTodos.value)
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/common.css';
input::-webkit-input-placeholder {
  font-style: italic;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.4);
}

input::-moz-placeholder {
  font-style: italic;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.4);
}

input::input-placeholder {
  font-style: italic;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.4);
}
h1 {
  position: absolute;
  top: -150px;
  width: 100%;
  font-size: 60px;
  font-weight: 200;
  text-align: center;
  color: #b83f45;
  -webkit-text-rendering: optimizeLegibility;
  -moz-text-rendering: optimizeLegibility;
  text-rendering: optimizeLegibility;
}

.new-todo {
  position: relative;
  margin: 0;
  width: 100%;
  font-size: 24px;
  font-family: inherit;
  font-weight: inherit;
  line-height: 1.4em;
  color: inherit;
  padding: 6px;
  border: 1px solid #999;
  box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
  box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  padding: 16px 16px 16px 60px;
  height: 65px;
  border: none;
  background: rgba(0, 0, 0, 0.003);
  box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03);
}

</style>

List.vue:

javascript 复制代码
<template>
  <section class="main">
    <!-- 全选按钮 -->
    <input type="checkbox" id="toggle-all" class="toggle-all" />
    <label for="toggle-all">全部完成</label>
    <!-- 待办事项列表 -->
    <ul class="todo-list">
      <li v-for="todo in filteredTodos" :key="todo.id" :class="{
        completed: todo.completed,
        editing: todo === editedTodo
      }">
        <div class="view">
          <input type="checkbox" class="toggle" v-model="todo.completed">
          <label @dblclick="editTodo(todo)">{{ todo.title }}</label>
          <button class="destroy" @click="removeTodo(todo)"></button>
        </div>
        <!-- 编辑框 -->
        <input type="text" class="edit" v-if="todo === editedTodo" v-model="todo.title"
          @keyup.ctrl.enter="doneEdit(todo)" @blur="doneEdit(todo)" @keyup.escape="cancelEdit(todo)"
          @vue:mounted="({ el }) => el.focus()" />
      </li>
    </ul>
  </section>
</template>

<script setup>
import { ref } from 'vue'
const todos = defineModel('todos')
const filteredTodos = defineModel('filteredTodos')

const editedTodo = ref() // 存储当前待办事项,默认值为Undefined
let beforeEditCache = '' // 缓存编辑前的标题,用于取消编辑时恢复

// 删除待办事项
function removeTodo(todo) {
  if (window.confirm('确定删除当前待办事项吗?')) {
    todos.value.splice(todos.value.indexOf(todo), 1)
  } else {
    todo.title = beforeEditCache
    beforeEditCache = ''
  }
}
// 编辑
function editTodo(todo) {
  editedTodo.value = todo
  beforeEditCache = todo.title
}

// 完成编辑方法
function doneEdit(todo) {
  if (editedTodo.value) {
    editedTodo.value = null // 只有置空了才会退出编辑模式
    todo.title = todo.title.trim()
    if (!todo.title) {
      removeTodo(todo)
    }
  } { }
}

// 取消编辑
function cancelEdit(todo) {
  editedTodo.value = null // 只有置空了才会退出编辑模式
  // 需要将标题还原
  todo.title = beforeEditCache
}

</script>

<style lang="scss" scoped>
@import '@/assets/common.css';
.edit {
  position: relative;
  margin: 0;
  width: 100%;
  font-size: 24px;
  font-family: inherit;
  font-weight: inherit;
  line-height: 1.4em;
  color: inherit;
  padding: 6px;
  border: 1px solid #999;
  box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
  box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.main {
  position: relative;
  z-index: 2;
  border-top: 1px solid #e6e6e6;
}

.toggle-all {
  width: 1px;
  height: 1px;
  border: none;
  /* Mobile Safari */
  opacity: 0;
  position: absolute;
  right: 100%;
  bottom: 100%;
}

.toggle-all+label {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 45px;
  height: 65px;
  font-size: 0;
  position: absolute;
  top: -65px;
  left: -0;
}

.toggle-all+label:before {
  content: '❯';
  display: inline-block;
  font-size: 22px;
  color: #949494;
  padding: 10px 27px 10px 27px;
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}

.toggle-all:checked+label:before {
  color: #484848;
}

.todo-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

.todo-list li {
  position: relative;
  font-size: 24px;
  border-bottom: 1px solid #ededed;
}

.todo-list li:last-child {
  border-bottom: none;
}

.todo-list li.editing {
  border-bottom: none;
  padding: 0;
}

.todo-list li.editing .edit {
  display: block;
  width: calc(100% - 43px);
  padding: 12px 16px;
  margin: 0 0 0 43px;
}

.todo-list li.editing .view {
  display: none;
}

.todo-list li .toggle {
  text-align: center;
  width: 40px;
  /* auto, since non-WebKit browsers doesn't support input styling */
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto 0;
  border: none;
  /* Mobile Safari */
  -webkit-appearance: none;
  appearance: none;
}

.todo-list li .toggle {
  opacity: 0;
}

.todo-list li .toggle+label {
  /*
		Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
		IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
	*/
  background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23949494%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');
  background-repeat: no-repeat;
  background-position: center left;
}

.todo-list li .toggle:checked+label {
  background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%2359A193%22%20stroke-width%3D%223%22%2F%3E%3Cpath%20fill%3D%22%233EA390%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22%2F%3E%3C%2Fsvg%3E');
}

.todo-list li label {
  word-break: break-all;
  padding: 15px 15px 15px 60px;
  display: block;
  line-height: 1.2;
  transition: color 0.4s;
  font-weight: 400;
  color: #484848;
}

.todo-list li.completed label {
  color: #949494;
  text-decoration: line-through;
}

.todo-list li .destroy {
  display: none;
  position: absolute;
  top: 0;
  right: 10px;
  bottom: 0;
  width: 40px;
  height: 40px;
  margin: auto 0;
  font-size: 30px;
  color: #949494;
  transition: color 0.2s ease-out;
}

.todo-list li .destroy:hover,
.todo-list li .destroy:focus {
  color: #c18585;
}

.todo-list li .destroy:after {
  content: '×';
  display: block;
  height: 100%;
  line-height: 1.1;
}

.todo-list li:hover .destroy {
  display: block;
}

.todo-list li .edit {
  display: none;
}

.todo-list li.editing:last-child {
  margin-bottom: -1px;
}

</style>

Footer.vue:

javascript 复制代码
<template>
  <footer class="footer">
    <span class="todo-count">
      <span>剩余 {{ remaining }} 项</span>
    </span>
    <ul class="filters">
      <li>
        <a href="#/all" :class="{ selected: visibility === 'all' }">全部</a>
      </li>
      <li>
        <a href="#/active" :class="{ selected: visibility === 'active' }">未完成</a>
      </li>
      <li>
        <a href="#/completed" :class="{ selected: visibility === 'complete' }">已完成</a>
      </li>
    </ul>
    <button class="clear-completed" @click="removeAllCompleted" v-show="todos.length > remaining">
      清除已完成
    </button>
  </footer>
</template>

<script setup>
const todos = defineModel('todos')
const remaining = defineModel('remaining')
const visibility = defineModel('visibility')
const emits = defineEmits(['removeAll'])

function removeAllCompleted() {
  emits('removeAll')
}
</script>

<style lang="scss" scoped>
@import '@/assets/common.css';
.footer {
  padding: 10px 15px;
  height: 20px;
  text-align: center;
  font-size: 15px;
  border-top: 1px solid #e6e6e6;
}

.footer:before {
  content: '';
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  height: 50px;
  overflow: hidden;
  box-shadow:
    0 1px 1px rgba(0, 0, 0, 0.2),
    0 8px 0 -3px #f6f6f6,
    0 9px 1px -3px rgba(0, 0, 0, 0.2),
    0 16px 0 -6px #f6f6f6,
    0 17px 2px -6px rgba(0, 0, 0, 0.2);
}

.todo-count {
  float: left;
  text-align: left;
}

.todo-count strong {
  font-weight: 300;
}

.filters {
  margin: 0;
  padding: 0;
  list-style: none;
  position: absolute;
  right: 0;
  left: 0;
}

.filters li {
  display: inline;
}

.filters li a {
  color: inherit;
  margin: 3px;
  padding: 3px 7px;
  text-decoration: none;
  border: 1px solid transparent;
  border-radius: 3px;
}

.filters li a:hover {
  border-color: #db7676;
}

.filters li a.selected {
  border-color: #ce4646;
}

.clear-completed,
html .clear-completed:active {
  float: right;
  position: relative;
  line-height: 19px;
  text-decoration: none;
  cursor: pointer;
}

.clear-completed:hover {
  text-decoration: underline;
}
</style>

todo.css:

css 复制代码
html,
body {
  margin: 0;
  padding: 0;
}

body {
  font:
    14px 'Helvetica Neue',
    Helvetica,
    Arial,
    sans-serif;
  line-height: 1.4em;
  background: #f5f5f5;
  color: #111111;
  min-width: 230px;
  max-width: 550px;
  margin: 0 auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-weight: 300;
}

.hidden {
  display: none;
}

.info {
  margin: 65px auto 0;
  color: #4d4d4d;
  font-size: 11px;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
  text-align: center;
}

.info p {
  line-height: 1;
}

.info a {
  color: inherit;
  text-decoration: none;
  font-weight: 400;
}

.info a:hover {
  text-decoration: underline;
}

/*
	Hack to remove background from Mobile Safari.
	Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio: 0) {
  .toggle-all,
  .todo-list li .toggle {
    background: none;
  }

  .todo-list li .toggle {
    height: 40px;
  }
}

@media (max-width: 430px) {
  .footer {
    height: 50px;
  }

  .filters {
    bottom: 10px;
  }
}

:focus,
.toggle:focus + label,
.toggle-all:focus + label {
  box-shadow: 0 0 2px 2px #cf7d7d;
  outline: 0;
}

common.css:

css 复制代码
/* 存储公共样式 */
button {
  margin: 0;
  padding: 0;
  border: 0;
  background: none;
  font-size: 100%;
  vertical-align: baseline;
  font-family: inherit;
  font-weight: inherit;
  color: inherit;
  -webkit-appearance: none;
  appearance: none;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

下一章 《Vue3 异步组件(懒加载组件)

相关推荐
阿里云云原生9 小时前
云栖实录:重构可观测 - 打造大模型驱动的云监控 2.0 与 AIOps 新范式
阿里云·云原生·重构·云监控·可观测
zuo-yiran11 小时前
vue div标签可输入状态下实现数据双向绑定
前端·javascript·vue.js
qq_3168377511 小时前
使用leader-line-vue 时垂直元素间距过小连线打转的解决
前端·javascript·vue.js
abiao198112 小时前
VUE的“单向数据绑定” 和 “双向数据绑定”
前端·javascript·vue.js
麦麦大数据13 小时前
F042 A星算法课程推荐(A*算法) | 课程知识图谱|课程推荐vue+flask+neo4j B/S架构前后端分离|课程知识图谱构造
vue.js·算法·知识图谱·neo4j·a星算法·路径推荐·课程推荐
拉不动的猪13 小时前
多窗口数据实时同步常规方案举例
前端·javascript·vue.js
南清的coding日记13 小时前
Java 程序员的 Vue 指南 - Vue 万字速览(01)
java·开发语言·前端·javascript·vue.js·css3·html5
Xiaouuuuua13 小时前
2026年计算机毕业设计项目合集
前端·vue.js·课程设计
shawn_yang13 小时前
实现公历和农历日期选择组件(用于选择出生日期)
vue.js·vant