【问题标题】:How can I make a Vue child component recognize that axios finished loading on Vue $root component?如何让 Vue 子组件识别 axios 在 Vue $root 组件上完成加载?
【发布时间】:2018-08-14 12:45:39
【问题描述】:

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

  • -main.js(= 根)
  • --App.vue
  • --- Navigation.vue(这个调用$root)

在 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
}

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

我很清楚“事件总线”、“道具”或“VueX”等其他方法,但我想使用带有 $root 组件的对话框并学习如何对异步做出反应——如果那样的话在这种情况下完全有可能。

【问题讨论】:

    标签: asynchronous vue.js axios vue-reactivity


    【解决方案1】:

    我不是 100% 确定,但在您的情况下,在您的子组件中创建 navItems 计算属性可能会起作用:

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

    这里有一个例子:http://jsfiddle.net/eywraw8t/268423/

    【讨论】:

    • 效果很好!你是个天才!非常感谢!
    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 2021-12-09
    • 2019-06-30
    • 2018-05-20
    • 2021-09-28
    • 2021-02-18
    • 2020-03-27
    • 2020-12-09
    相关资源
    最近更新 更多