Vue 组件生命周期:使用 Axios 获取数据并渲染任务清单
<script>
import TodoList from "@/components/TaskList/TodoList";
import TodoInput from "@/components/TaskList/TodoInput";
import TodoButton from "@/components/TaskList/TodoButton";
export default {
name: "TaskList",
async created() {
await this.getData();
},
data() {
return {
todolist: [],
nextId: 0,
activeBtnIndex: 2,
};
},
computed: {
TaskList() {
switch (this.activeBtnIndex) {
case 0:
return this.todolist;
case 1:
return this.todolist.filter((x) => x.done === true);
case 2:
return this.todolist.filter((x) => x.done !== true);
}
},
},
methods: {
async getData() {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/todos");
if (response.status === 200) {
this.todolist = response.data.slice(0, 5).map((item) => ({
id: item.id,
task: item.title,
done: item.completed,
}));
this.nextId = this.todolist.length;
} else {
console.log("获取数据失败");
}
} catch (error) {
console.log(error);
console.log("获取数据失败");
}
},
onAddNewTask(taskname) {
this.todolist.push({
id: this.nextId,
task: taskname,
done: false,
});
this.nextId++;
},
},
components: {
TodoList,
TodoInput,
TodoButton,
},
};
</script>
原文地址: https://www.cveoy.top/t/topic/mj6x 著作权归作者所有。请勿转载和采集!