mirror of
https://github.com/youzan/vant.git
synced 2025-10-22 11:54:02 +00:00
[improvement] add portal mixin (#3583)
This commit is contained in:
48
packages/mixins/portal.js
Normal file
48
packages/mixins/portal.js
Normal file
@@ -0,0 +1,48 @@
|
||||
function getElement(selector) {
|
||||
if (typeof selector === 'string') {
|
||||
return document.querySelector(selector);
|
||||
}
|
||||
|
||||
return selector();
|
||||
}
|
||||
|
||||
export function PortalMixin({ afterPortal }) {
|
||||
return {
|
||||
props: {
|
||||
getContainer: [String, Function]
|
||||
},
|
||||
|
||||
watch: {
|
||||
getContainer() {
|
||||
this.portal();
|
||||
}
|
||||
},
|
||||
|
||||
mounted() {
|
||||
if (this.getContainer) {
|
||||
this.portal();
|
||||
}
|
||||
},
|
||||
|
||||
methods: {
|
||||
portal() {
|
||||
const { getContainer } = this;
|
||||
|
||||
let container;
|
||||
if (getContainer) {
|
||||
container = getElement(getContainer);
|
||||
} else if (this.$parent) {
|
||||
container = this.$parent.$el;
|
||||
}
|
||||
|
||||
if (container && container !== this.$el.parentNode) {
|
||||
container.appendChild(this.$el);
|
||||
}
|
||||
|
||||
if (afterPortal) {
|
||||
afterPortal.call(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
Reference in New Issue
Block a user