Vue.js 页面跳转后立即发送 Axios POST 请求获取数据
<script>
import axios from 'axios'
import TodoList from "@/components/TaskList/TodoList";
import TodoInput from "@/components/TaskList/TodoInput";
import TodoButton from "@/components/TaskList/TodoButton";
export default {
name: "TaskList",
data() {
return {
todolist: [],
nextId: 1,
activeBtnIndex: 2
}
},
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,
},
created() {
axios.post('/api/getData').then(res => {
this.todolist = res.data
this.nextId = this.todolist.length + 1
}).catch(error => {
console.log(error)
})
},
}
</script>
<p>在以上代码中,我们使用了 axios 库发送 POST 请求来获取数据,请求的地址是 '/api/getData',然后将返回的数据存储到 todolist 数组中,并将 nextId 设置为 todolist 的长度加 1。注意,这里的请求地址是示例代码中的地址,具体的地址需要根据实际情况进行修改。</p>
<p>通过在 created 生命周期钩子函数中发送 Axios POST 请求,并在请求成功后将数据存储到 data 中,可以实现页面跳转后立即发送请求并获取动态数据,从而让页面加载时展示最新的数据。</p>
原文地址: https://www.cveoy.top/t/topic/mlW7 著作权归作者所有。请勿转载和采集!