我有这个应用程序结构
<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>
如您所见,有两个组件和路由器视图。
路由器视图包含API中列出的产品,这些产品可以添加到包组件中。
在我的产品视图中(路由器视图的一部分)我有方法将项目添加到包中 - 基本上将POST HTTP请求发送到服务器
addToBag() {
productService.add(this.item)
.then(item => {
console.log('sucess !)
})
}
这项工作,但只有在重装后,我才能看到包里的物品。
调度事件是可以工作的事情,但组件层次结构不允许我使用它。
答案 0 :(得分:1)
您正在添加项目服务器端。您还需要将该项添加到vm.bag
数据中。您可能想要使用Vuex
。基本上,你需要的是获得相同的&#34; bag&#34;来自您的bag
组件(您已经拥有)和来自您的&#34; productService&#34;或者&#34; addToBag&#34;方法
因此,在您声明bag
数据的组件中,您应该更改:
// from
/* inside component */
data: function() {
return {
bag: []
}
}
// to
var state = {
bag: []
}
/* inside component */
data: function() {
return {
bag: state.bag
}
}
然后,您在bag
方法中使用相同的addToBag
数组:
addToBag() {
productService.add(this.item)
.then(item => {
state.bag.push(item)
})
}