如何让 Vue 子组件识别出 axios 在 Vue $root 组件上完成加载?

How can I make a Vue child component recognize that axios finished loading on Vue $root component?

我的小 Vue 应用程序的基本设置遵循基本的 Vue Cli 3 设置:

在 main.js 的 created() 中,有这个函数可以为导航菜单加载 json:

[...]
data() {
    return {
        navMainItems: null
        staticTestItems: [
            { "id": 0, "title": "test 1, "url": "/" },
            { "id": 1, "title": "test 2, "url": "/" }
        ]
    }
},
created() {
    axios.get('navigation/navAllItems.json')
        .then((response) => {
            this.navMainItems = response.data.navMainItems;
    [...]
}

效果很好。 现在我想使用 "this.$root":

从 Navigation.vue 组件调用该数据
data(){
  return {
    navItems: null,
    localStaticTestItems: this.$root.staticTestItems
  }
},
created() {
    // Check if static elements loaded
    console.log("sampleNavItems =", this.$root.sampleNavItems)
},
mounted(){
  // This fails, presumably because of asynchonicity
  // Can this be fixed?
  this.navItems = this.$root.navMainItems
}

虽然静态元素加载得很好,但异步加载的导航项不会更新。

我很清楚其他方法,如 "event bus"、"props" 或 "VueX",但我想使用带有 $root 组件的对话框并了解如何使用对异步性做出反应 - 如果在这种情况下完全可能的话。

我不是 100% 确定,但在你的情况下,在你的子组件中制作 navItems 计算 属性 可能有效:

  computed: {
    navItems() { return this.$root.navMainItems }
  }

这是一个 fiddle 示例:http://jsfiddle.net/eywraw8t/268423/