Vue.js 中使用 Axios 在页面加载时发送请求并存储数据
<script>
import TodoList from "@/components/TaskList/TodoList";
import TodoInput from "@/components/TaskList/TodoInput";
import TodoButton from "@/components/TaskList/TodoButton";
import axios from 'axios';
export default {
name: "TaskList",
data() {
return {
todolist: [],
nextId: 0,
activeBtnIndex: 2
}
},
created() {
axios.get('http://example.com/api/tasks')
.then(response => {
this.todolist = response.data;
this.nextId = response.data.length;
})
.catch(error => {
console.log(error);
});
},
computed: {
// eslint-disable-next-line vue/return-in-computed-property
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: {
onAddNewTask(taskname) {
this.todolist.push({
id: this.nextId,
task: taskname,
done: false
})
this.nextId++
}
},
components: {
TodoList,
TodoInput,
TodoButton,
}
}
</script>
<p>在 Vue.js 中,可以使用 <code>created()</code> 生命周期钩子函数在组件创建时发送 Axios 请求。<code>created()</code> 钩子函数在组件实例创建完成后立即调用,此时组件的 data 属性已创建,可以使用 <code>this</code> 访问。</p>
<p>在这个例子中,我们在 <code>created()</code> 中使用 Axios 发送 GET 请求到 <code>http://example.com/api/tasks</code> 接口,获取任务列表数据。</p>
<ul>
<li><code>axios.get()</code> 方法发送 GET 请求,参数为请求 URL。</li>
<li><code>then()</code> 方法用于处理请求成功后的回调,将响应数据存储在 <code>todolist</code> 数组中,并将 <code>nextId</code> 设置为当前任务数量。</li>
<li><code>catch()</code> 方法用于处理请求失败后的回调,将错误信息打印到控制台。</li>
</ul>
<p>通过这种方式,我们可以在页面加载时使用 Axios 发送请求获取数据,并将数据存储在组件的 data 中,方便在组件内使用。</p>
原文地址: https://www.cveoy.top/t/topic/mlUJ 著作权归作者所有。请勿转载和采集!