vue3 - JSON-SERVER Todolist get, post, delete, patch

developer.do·2023년 5월 5일
0

addTodo 하는법

get

  const getTodos = async () => {
      try {
        const res = await axios.get('http://localhost:3000/todos')  // todos api에서 받아온다.
        console.log('res', res.data)  // res.data에는 todos db에 저장된 데이터가 들어있다.
        todos.value = res.data // 따라서 todos라는 array에 res.data를 넣어주는 것이다.
      }
      catch (err) {
        console.log(err.data)
      }
    }

post


const addTodo = async (todo) => {
      error.value = '' 

      try {
        const res = await axios.post('http://localhost:3000/todos', {
          subject: todo.subject,
          completed: todo.completed,
        })
        todos.value.push(res.data)
        console.log(res, 'res')
      }
      catch (err) {
        console.log(err)
      }
    }

delete

db로 삭제 요청을 보내보자

  const deleteTodo = async (index) => {  // 
      const id = todos.value[index].id // todos.value[0].id 즉 내가 삭제할려는 todo의 id가 필요함. 그러면 index값을 받아와야지 알 수 있는거임
      try {
        const res = axios.delete(`http://localhost:3000/todos/${id}`) // 여기서 내가 삭제하고 싶은 그 
        todos.value.splice(index, 1)
      }
      catch (err) {
        console.log(err)
      }
    }

patch

todoDone을 서버에 업데이트 해보자


    const toggleTodo = async (index) => {
      const id = todos.value[index].id // 내가 클릭한 todo의 id가 필요함
      try {
        await axios.patch(`http://localhost:3000/todos/${id}`, { 
          completed: !todos.value[index].completed, // 수정을 해준다. completed 부분을, 반대로

        })
        todos.value[index].completed = !todos.value[index].completed // 그다음 배열도 업데이트 해준다.
      }
      catch (err) {
        console.log(err)
      }
    }

0개의 댓글