使用场景:由于vue有$parent属性可以让子组件访问父组件。但孙组件想要访问祖先组件就比较困难。通过provide/inject可以轻松实现跨级访问祖先组件的数据
父页面注入
import { getQueryString } from 'utils/helper';
import { get_menu_permission } from 'api/cooperation-in-page';
export default {
name: 'MyBusinessBusinessDetails',
components: {
BusinessInfo,
MoreHandle,
// LinkCompany,
FollowRecords,
BusinessDemandInfo,
BusinessRole,
},
provide() {
return {
permissionType: this.permissionInfo,
};
},
data() {
return {
businessId: '',
from: '',
permissionInfo: {},
};
},
created() {
let query = new getQueryString();
this.businessId = query?.businessId;
this.from = query?.from;
console.log(this.from, 'this.from');
this.getMenuPermission(this.businessId);
},
methods: {
//获取操作合作联盟操作权限
getMenuPermission(bizId) {
const params = { bizId };
get_menu_permission(params).then(({ code, data }) => {
if (code === 200) {
this.permissionInfo.info = data;
}
});
},
},
};
</script>
提示:provide 和 inject 绑定并不是可响应的,这是一个坑。然而,如果你传入了一个可监听的对象,那么其对象的属性还是可响应的 permissionInfo: {},
子组件使用
inject: ['reload', 'permissionType'],
console.log('exist=======', this.permissionType.info);