vuex全家桶系列12-路由组件内在什么时机获取数据

171 阅读1分钟

1.数据的获取以及 vue.config.js 制作假数据:

1.1-数据的获取:

有时候,进⼊某个路由后,需要从服务器获取数据。例如,在渲染⽤户信息时,你需要从服务器获取⽤户的数据。可以通过两种⽅式来实现:

  • 导航完成之后获取:先完成导航,然后在接下来的组件⽣命周期钩⼦中获取数据。在数据获取期间显示“加载中”之类的指示。
  • 导航完成之前获取:导航完成前,在路由进⼊的守卫中获取数据,在数据获取成功后执⾏导航。导航完成后获取数据

1.2- vue.config.js 制作假数据:

  • 项目根目录下创建一个文件 vue.config.js :
//vue.config.js
module.exports ={
    devServer:{
        before:(app,serve)=>{
            app.get("/api/post",(req,res)=>{
                res.json({
                    lover:"linlin",
                    promise:"爱是想要触碰有收回的手,在导航完成之后获取数据"
                })
            })
        }
    }
}
  • 然后保存并通过 npm run serve 重启项目,可以通过 http://localhost:8080/api/post 访问到自己本地配置的假数据
  • 顺便 npm install axios -S 安装 axios
  • main.js 中挂载 axios
import Vue from 'vue'
import App from './App.vue'

import router from "./router";
import axios from "axios";

Vue.prototype.$http = axios;

Vue.config.productionTip = false
//...省略
new Vue({
  //4、挂载到vue实例上
  router,
  render: h => h(App)
}).$mount('#app')

2.Post组件数据的加载

  • 使用 axios($http) 去发送请求
  • 通过 asyncawait 去同步化请求
  • 通过 try-catch 来处理错误信息
<template>
<div>
    <div class="post">
        <div v-if="loading" class="loading">Loading</div>
        <div v-if="error" class="error">{{error}}</div>
        <div v-if="post">
            <h3>{{post.lover}}</h3>
            <h3>{{post.promise}}</h3>
        </div>
    </div>
</div>
</template>

<script>
export default {
    data() {
        return {
            post: null,
            error: null,
            loading: false
        }
    },
    created() {
        console.log(this.$http);
        this.getData();
    },
    watch: {
        //当路由发生变化的时候,就去请求对应的数据
        $route: "getData"
    },
    methods: {
        async getData() {
            try {
                this.loading = true
                const res = await this.$http.get("/api/post");
                console.log(res);
                this.loading = false
                this.post = res.data
            } catch (error) {
                console.log(error)
                this.error = error.toString();
            }
        }
    }
}
</script>

😁这样就完成了导航加载之后获取数据的操作。