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