javascript - vue 、 vue-resource 同步问题

查看:143
本文介绍了javascript - 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>

这篇关于javascript - vue 、 vue-resource 同步问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆