业务需求: 父级页面请求数据,在子级和孙级等组件中都要使用,不确定几层,为了避免每个页面重复请求和过多的props,因此使用provide / inject进行实现.
在父组件中provide 返回要传给下级的数据
/*provide 和 data 同一层级*/
provide() {
return{
publicCategories: () => {
return this.categoryList },
publicBrandList:()=>{
return this.brandList},
publicSupplierList:()=>{
return this.supplierList},
publicWarehouseList:()=>{
return this.warehouseList},
getCategoryList:() => {
this.getCategoryList() },
getBrandList:()=>{
this.getBrandList() }
}
},
在子孙级组件中inject 接受父级传的数据
// 同样,inject 和 data也是同级
inject: ['publicCategories','publicBrandList','publicSupplierList','publicWarehouseList','getCategoryList'],
// 使用方法
data(){
return {
categories: this.publicCategories() // 这是父组件传的值
}
},
methods:{
// 在子孙级页面声明方法,可直接调用父组件传的方法
click(){
this.getCategoryList()
}
}
这个一般不常用,记录一下.