VueRouter进阶三(数据获取)

数据获取

工具

咱们可使用 ajax 等工具.vue

咱们这里使用了vue-resourcegit

地址:
https://github.com/pagekit/vu...github

导航完成后获取数据

当你使用这种方式时,咱们会立刻导航和渲染组件,而后在组件的 mounted 钩子中获取数据。这让咱们有机会在数据获取期间展现一个 loading 状态,还能够在不一样视图间展现不一样的 loading 状态。ajax

component:{
    data:function(){
        return {
            shuju:[]
        }
    },
    template:`
            <ul>
                <li v-for="(shujuy , i) in shuju" :key="i">{{shujuy.name}}</li>
            </ul>
        `,
    mounted:function(){
        this.$http.get(url).then(response => {
            this.shuju = response.body;
        }, response => {

        });
    }
}

在导航完成前获取数据

经过这种方式,咱们在导航转入新的路由前获取数据。咱们能够在接下来的组件的 beforeRouteEnter 钩子中获取数据,当数据获取成功后只调用 next 方法。vue-resource

beforeRouteEnter (to, from, next) {
    Vue.http.get(url).then(response => {
    vm.no = false
    vm.shuju = response.body;
    next();
    }, response => {
    next("/")
}},

详细资料:https://github.com/Smallmotor...工具

相关文章
相关标签/搜索