首页 > vue 、 vue-resource 同步问题

vue 、 vue-resource 同步问题

基于vue 、 vue-router 、vue-resource 做的一个单页面应用
现在有个需求是 父级路由页面先获取后台数据,子级路由页面根据父级数据进行展示或数据请求。首先想到用同步 但vue-resource里面好像并没有 , 请问大神们怎么破


router-view 可以傳遞 prop

<router-view :prop="prop"></router-view>

可以利用這個特性來在嵌套的路由中傳遞數據

假設現在路由如下:

router.map({
  '/': {
    name: 'index',
    component: HomePage
   },
  '/posts': {
    name: 'posts',
    component: PostsPage,
    subRoutes: {
      'list': {
        name: 'list',
        component: PostListPage,
      },
      'random': {
        name: 'random',
        component: RandomPostPage,
      }
    }
  },
})

那現在要在 PostsPage 中取得全部文章,並提供給底下兩個子路由 lists, random 使用:

PostsPage

<template>

<div class="posts">
   <a v-link="{name: 'list'}">列表</a> | <a v-link="{name: 'random'}">隨機</a>
   <router-view :posts="posts"></router-view>
</div>

</template>

<script>

export default {
    route: {
      data: function (transition) {
        return this.$http.get(API.posts).then(res => {
            return { posts: res.json() }
        })
      }
    },
    data() {
        return {
            posts: []
        }
    }
}

</script>

這樣子路由就可以透過 props 拿到數據:

PostListPage

<template>

<div class="page">
    <ul>
        <li v-for="post in posts">
            <a v-link="{name: 'post', params: {id: post.id}}">{{ post.title }}</a>
        </li>
    </ul>
</div>

</template>

<script>

export default {
  props: ['posts']
}

</script>

父级组件发起数据请求 父级组件渲染子级组件
子级组件通过prop获得父级组件数据 但是由于此时尚未发起/获得ajax数据 判断并显示为loading状态
父级数据请求成功/失败 根据预设回调行为自动同步(prop)下去 或者切换到加载失败组件
子级组件prop自动更新为新数据 自动把状态切为正常显示

-------vuejs的使用和文档都非常清晰,基本上看到就知道应该怎么办了
http://vuejs.org.cn/guide/components.html#Props
看文档感觉比看我这一段话来得更舒服

当然也可能你最异步编程这一块比较不熟
若解决不了,可考虑上传代码到gist补充到题目中
或者评论我让我给你更具体的解答

【热门文章】
【热门文章】