>웹 프론트엔드 >JS 튜토리얼 >Vue.js의 간단한 할 일 목록 애플리케이션 단계별 가이드

Vue.js의 간단한 할 일 목록 애플리케이션 단계별 가이드

王林
王林원래의
2024-09-05 06:35:09697검색

Simple To-Do List Application in Vue.js Step-by-Step Guide

이 가이드는 Vue.js 3을 사용하여 기본 To-Do List 애플리케이션을 구축하는 과정을 안내합니다. 이 튜토리얼이 끝나면 데이터 바인딩, 이벤트 처리 방법을 이해하게 됩니다. Vue.js의 처리 및 동적 렌더링.

전제조건

HTML, CSS, JavaScript에 대한 기본 지식
컴퓨터에 Node.js와 npm이 설치되어 있습니다.
Vue CLI가 설치되었습니다. 그렇지 않은 경우 npm install -g @vue/cli를 실행하여 설치할 수 있습니다.

1단계: 프로젝트 설정

새 Vue.js 프로젝트 만들기: 터미널을 열고 다음 명령을 실행하여 새 Vue.js 3 프로젝트를 만듭니다.

vue create todo-app

프로젝트 디렉토리로 이동하세요:

cd todo-app

개발 서버 실행: Vue 개발 서버 시작:

npm run serve

이렇게 하면 브라우저의 http://localhost:8080에 기본 Vue.js 시작 템플릿이 열립니다.

2단계: 애플리케이션 구조화

기본 템플릿 정리: src/App.vue를 열고 기본 템플릿, 스크립트 및 스타일 콘텐츠를 제거합니다. 다음 코드로 바꾸세요.

<template>
  <div id="app">
    <h1>Vue.js To-Do List</h1>
    <input v-model="newTask" placeholder="Add a new task">
    <button>Add Task</button>
    <ul>
      <li v-for="(task, index) in tasks" :key="index">
        <input type="checkbox" v-model="task.completed">
        <span :class="{ 'completed-task': task.completed }">{{ task.text }}</span>
        <button>Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      newTask: '',
      tasks: []
    };
  },
  methods: {
    addTask() {
      if (this.newTask.trim() !== '') {
        this.tasks.push({ text: this.newTask, completed: false });
        this.newTask = '';
      }
    },
    removeTask(index) {
      this.tasks.splice(index, 1);
    }
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.completed-task {
  text-decoration: line-through;
  color: grey;
}
input {
  margin-bottom: 10px;
  padding: 5px;
}
button {
  margin-left: 5px;
  padding: 5px;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px 0;
}
</style>

3단계: 코드 이해

템플릿 섹션:


: 이 입력 필드는 v-model을 사용하여 newTask 데이터 속성에 바인딩되므로 양방향 데이터 바인딩이 가능합니다. @keyup.enter="addTask"는 addTask 메소드를 트리거하기 위해 Enter 키를 수신합니다.


: 이 버튼을 클릭하면 addTask 메소드가 실행됩니다.

    : 이 순서가 지정되지 않은 목록은 v-for를 사용하여 작업 배열을 반복하고 각 작업을 렌더링합니다. :key="index"는 Vue에서 목록 항목을 효율적으로 추적하는 데 필요한 각 항목의 고유 식별자입니다.

    : 작업 완료 상태를 전환하는 체크박스입니다.

    {{ task.text }} : 범위 요소는 작업 텍스트를 표시합니다. :class 지시문은 작업 완료 여부에 따라 Completed-task CSS 클래스를 조건부로 적용합니다.

    : 목록에서 작업을 제거하는 버튼

    스크립트 섹션:

    data() 메서드:
    newTask: 추가할 새 작업의 값을 보유하는 문자열입니다.
    작업: 모든 작업을 보유하는 배열로, 각 작업은 텍스트와 완료된 속성이 있는 객체로 표시됩니다.

    메서드 객체:
    addTask(): 이 메서드는 newTask를 작업 배열에 추가한 다음 newTask 입력 필드를 지웁니다.
    RemoveTask(index): 이 메소드는 해당 인덱스를 기반으로 작업 배열에서 작업을 제거합니다.

    스타일 섹션:

    완료된 작업을 완료하는 .completed-task 클래스를 사용하여 할 일 목록 스타일을 지정하는 기본 CSS입니다.

    로컬 저장소에 작업 유지: 브라우저의 로컬 저장소에 작업을 저장하여 페이지를 다시 로드해도 작업이 유지되도록 하여 앱을 향상할 수 있습니다.

mounted() {
  this.tasks = JSON.parse(localStorage.getItem('tasks')) || [];
},
methods: {
  addTask() {
    if (this.newTask.trim() !== '') {
      this.tasks.push({ text: this.newTask, completed: false });
      this.newTask = '';
      localStorage.setItem('tasks', JSON.stringify(this.tasks));
    }
  },
  removeTask(index) {
    this.tasks.splice(index, 1);
    localStorage.setItem('tasks', JSON.stringify(this.tasks));
  }
}

편집 작업:

<template>
  <div id="app">
    <h1>Vue.js To-Do List</h1>
    <input v-model="newTask" placeholder="Add a new task">
    <button>Add Task</button>
    <ul>
      <li v-for="(task, index) in tasks" :key="index">
        <input type="checkbox" v-model="task.completed">

        <span v-if="!task.isEditing" :class="{ 'completed-task': task.completed }">{{ task.text }}</span>
        <input v-else v-model="task.text">

        <button v-if="!task.isEditing">Edit</button>
        <button>Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      newTask: '',
      tasks: []
    };
  },
  methods: {
    addTask() {
      if (this.newTask.trim() !== '') {
        this.tasks.push({ text: this.newTask, completed: false, isEditing: false });
        this.newTask = '';
      }
    },
    removeTask(index) {
      this.tasks.splice(index, 1);
    },
    editTask(task) {
      task.isEditing = true;
    },
    saveTask(task) {
      task.isEditing = false;
    }
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.completed-task {
  text-decoration: line-through;
  color: grey;
}
input {
  margin-bottom: 10px;
  padding: 5px;
}
button {
  margin-left: 5px;
  padding: 5px;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px 0;
}
</style>

Font Awesome 설치

먼저 프로젝트에 Font Awesome을 포함하세요. CDN을 사용하는 경우 이 링크를 HTML 파일에 추가하거나 index.html의

섹션에 직접 추가할 수 있습니다.


** 아이콘으로 템플릿 업데이트
**

이제 작업 편집, 삭제, 완료를 위한 Font Awesome 아이콘을 추가해 보겠습니다.

<template>
  <div id="app" class="container">
    <h1>Vue.js To-Do List</h1>
    <div class="input-container">
      <input v-model="newTask" placeholder="Add a new task">
      <button class="btn btn-add"><i class="fas fa-plus"></i></button>
    </div>
    <ul>
      <li v-for="(task, index) in tasks" :key="index" :class="{ completed: task.completed }">
        <input type="checkbox" v-model="task.completed" id="checkbox">

        <span v-if="!task.isEditing" class="task-text">{{ task.text }}</span>
        <input v-else v-model="task.text" class="edit-input">

        <div class="actions">
          <button v-if="!task.isEditing" class="btn btn-edit"><i class="fas fa-edit"></i></button>
          <button class="btn btn-delete"><i class="fas fa-trash-alt"></i></button>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      newTask: '',
      tasks: []
    };
  },
  methods: {
    addTask() {
      if (this.newTask.trim() !== '') {
        this.tasks.push({ text: this.newTask, completed: false, isEditing: false });
        this.newTask = '';
      }
    },
    removeTask(index) {
      this.tasks.splice(index, 1);
    },
    editTask(task) {
      task.isEditing = true;
    },
    saveTask(task) {
      task.isEditing = false;
    }
  }
};
</script>

<style>
body {
  background-color: #f4f7f6;
  font-family: 'Roboto', sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  padding: 20px;
  max-width: 400px;
  width: 100%;
}

h1 {
  color: #333;
  margin-bottom: 20px;
}

.input-container {
  display: flex;
  margin-bottom: 20px;
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 16px;
}

.btn {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 5px;
  transition: background-color 0.3s;
}

.btn:hover {
  background-color: #45a049;
}

.btn-add {
  background-color: #28a745;
}

.btn-edit {
  background-color: #ffc107;
}

.btn-delete {
  background-color: #dc3545;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
  background-color: #f8f9fa;
}

li.completed .task-text {
  text-decoration: line-through;
  color: #888;
}

li:hover {
  background-color: #e9ecef;
}

.actions {
  display: flex;
}

.actions .btn {
  margin-left: 5px;
}

.edit-input {
  flex: 1;
  margin-right: 10px;
}
</style>

위 내용은 Vue.js의 간단한 할 일 목록 애플리케이션 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.