【问题标题】:Passing props to nested route将 props 传递给嵌套路由
【发布时间】:2017-10-14 21:05:37
【问题描述】:

我的 VueJS 应用程序中有以下路线:

const routes = [
  {
    path: '/',
    component: PlacesList
  },
  {
    name: 'place',
    path: '/places/:name',
    component: CurrentWeather,
    children: [
      {
        name: 'alerts',
        path: 'alerts',
        component: ForecastAlerts
      },
      {
        name: 'forecast',
        path: 'forecast',
        component: ForecastTimeline
      }
    ]
  }
];

ForecastTimeline 接收从CurrentWeather 传递的道具:

export default {
  name: 'ForecastTimeline',
  props: ['forecastData'],
  components: {
    ForecastDay
  }
}

当我从 /places/:name 导航到 /places/:name/forecast 时,一切正常。但是,当我尝试直接访问/places/:name/forecast 时,我收到Cannot read property 'summary' of undefined 错误。这是因为forecastData 是在CurrentWeather 组件中异步获取的。处理传递给嵌套路由的异步属性的正确方法是什么?

【问题讨论】:

  • 您是否尝试过将 prop 定义移动到 mixin 中?这样您就可以将它作为来自同一来源的ForcastAlertsForcastTimeline 的一部分。我能想到的另一个选择是使用 Vuex 存储来使数据可跨组件访问。
  • 我还没有尝试过mixin。 Vuex 是我计划在未来添加的东西,但我想弄清楚如何在没有它的情况下实现这一点。
  • 我认为最好的其他方法是让 ForcastTimeline 组件在全局消息泵上定义一个事件,以便无论检索数据的内容如何都可以调用它
  • 您可以尝试在 ForecastTimeline 组件中添加 beforeRouteEnter() 并检查异步任务是否完成,然后只能访问数据

标签: vue.js vuejs2 vue-component vue-router


【解决方案1】:

您是否尝试过在获取数据时不显示子路由组件?

类似:

export default {
  name: 'CurrentWeather',
  data(){
    return {
      loading: true
    }
  },
  created(){
    this.fetchForecastData().then(() => {
      this.loading = false;
    });
  },
  methods: {
    fetchForecastData() {
      return fetch('http://..');
    }
  }
}

在 CurrentWeather 模板中:

<router-view v-if="!loading"></router-view>

【讨论】:

    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多