在对另一个组件执行http请求时保持响应性

Keeping reactivity while doing http request into another component

本文关键字:响应 请求 http 另一个 组件 执行      更新时间:2023-09-26

我有这个应用程序结构

<header-bar></header-bar>    
<bag :bag="bag"></bag>
<!--Main Section-->
<section class="MainSection">
    <div class="MainSection__wrap">
        <router-view 
            is="view" 
            transition="fade" 
            transition-mode="out-in"
            keep-alive
        >
        </router-view>
    </div>
</section>

如你所见,有2个组件和路由器视图。

路由器视图包含API中列出的产品,这些产品可以添加到bag组件中。

在我的产品视图(路由器视图的一部分),我有一个方法,添加项目到包-基本上使POST HTTP请求服务器

addToBag() {
   productService.add(this.item)
      .then(item => {
          console.log('sucess !)
      })
}

和这个工作,但只有重新加载后,我才能看到包里的物品。

调度事件是可以工作的,但是组件层次结构不允许我使用它

您正在服务器端添加项。您还需要将该项目添加到vm.bag数据中。你可能想用Vuex。基本上,你需要的是从你的bag组件(你已经有)从你的"productService"或"addToBag"方法访问相同的"包"。

因此,在声明bag数据的组件中,您应该更改:

// from
    /* inside component */
    data: function() {
        return {
            bag: []
        }
    }

// to
var state = {
    bag: []
}
    /* inside component */
    data: function() {
        return {
            bag: state.bag
        }
    }
然后,在addToBag方法中使用相同的bag数组:
addToBag() {
   productService.add(this.item)
      .then(item => {
          state.bag.push(item)
      })
}