vue-cli學習-路由資料獲取
阿新 • • 發佈:2021-09-22
vue-cli學習-路由資料獲取
路由資料獲取
獲取資料,可以有兩種方式:導航完成後獲取和導航完成前獲取
導航完成後獲取
編寫post.vue,並配置好路由規則
<template> <div class="post"> <div v-if="loading"> loading </div> <div v-if="post"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> </div> </template> <script> export default { name: "Post", data() { return { loading: false, post: null } }, //元件建立完畢 created() { //執行獲取資料 this.getData() }, methods:{ //獲取資料 getData(){ this.loading=true //開始獲取資料 setTimeout(()=>{ //關閉loading this.loading=false, this.post={ title:'標題', body:'內容' } },1000) } } </script> <style scoped> </style>
完成後獲取
使用元件內守衛 beforeRouterEnter 實現
<script> export default { name: "Post", data() { return { loading: false, post: null } }, beforeRouteEnter(to, from, next) { setTimeout(()=>{ next(vm =>{ vm.getData() } ) },2000) }, methods: { //獲取資料 getData() { this.post = { title: '標題', body: '內容' } } } } </script>