如何在父组件数组中添加新的Task?

问题描述 投票:0回答:0

我希望添加一个新的任务对象,并通过单击“添加”按钮在父组件数组中将其可视化。但是我有一个错误 newTask is not defined。即使我在子组件中形成 newTasks 并将其传递给 vuex 中的父数组。

https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-bkwixg?file=store%2Findex.js,components%2FTask.vue,pages%2Findex.vue

// Child component

methods: {
    addTask() {
      let newTask = {
        id: Math.floor(Math.random() * 25),
        title: this.title,
        completed: false,
      };
      if (newTask) {
        console.log(newTask);
        this.$store.dispatch('addTask', newTask);

        this.title = '';
      }
    },
  }
  
  // Store
  
  export const state = () => ({
  tasks: [],
});
  
  const actions: {
    async addTask(context, data) {
    data = {
      ...data,
      newTask,                        // getting an error here - newTask is not defined
 
    };
    const res = await fetch('https://jsonplaceholder.typicode.com/todos', {
      method: 'POST',
      headers: {
        'Content-Type': 'appication/json;charset=utf-8',
      },
      body: JSON.stringify(data),
    });
    if (res.ok) {
      let result = await res.json();
      context.dispatch('getTasks');
    }
    return res.ok;
  },
  }
  
  const mutations: {
    setTasks(state, data) {
    state.tasks = data;
    },
  }

商店

javascript vue.js post nuxt.js vuex
© www.soinside.com 2019 - 2024. All rights reserved.