vue组件内的元素转移到指定位置
应⽤场景:
组件内的dom默认是在组件内,有时候会出现⼀些问题:我们封装的组件使⽤了actionsheet 啊,popup啊,这些如果不直接在body下,会出现⼀些样式层叠问题(因为z-index)。这时候如果可以将引发问题的dom 挪到body下,就好了。
⼀些理解:
1、来源
2、代码思想
⽤⼀个注释标签替换⽬标元素,⽬标元素被挪到指定的元素下(默认body)。
学习代码:
// Thanks to: github/calebroseland/vue-dom-portal
/**
* Get target DOM Node
* @param {(Node|string|Boolean)} [node=document.body] DOM Node, CSS selector, or Boolean
* @return {Node} The target that the el will be appended to
*/
function getTarget (node) {
if (node === void0) {
return document.body
}
if (typeof node === 'string' && node.indexOf('?') === 0) {
return document.body
} else if (typeof node === 'string' && node.indexOf('?') > 0) {
node = node.split('?')[0]
}
if (node === 'body' || node === true) {
return document.body
nodeselector}
return node instanceof window.Node ? node : document.querySelector(node)
}
function getShouldUpdate (node) {
// do not updated by default
if (!node) {
return false
}
if (typeof node === 'string' && node.indexOf('?') > 0) {
try {
const config = JSON.parse(node.split('?')[1])
return config.autoUpdate || false
} catch (e) {
return false
}
}
return false
}
const directive = {
inserted (el, { value }, vnode) {
el.className = el.className ? el.className + ' v-transfer-dom' : 'v-transfer-dom'
const parentNode = el.parentNode
var home = ateComment('')
var hasMovedOut = false
if (value !== false) {
getTarget(value).appendChild(el) // moving into new place
hasMovedOut = true
}
if (!el.__transferDomData) {
el.__transferDomData = {
parentNode: parentNode,
home: home,
target: getTarget(value),
hasMovedOut: hasMovedOut
}
}
},
componentUpdated (el, { value }) {
const shouldUpdate = getShouldUpdate(value)
if (!shouldUpdate) {
return
}
// need to make sure children are done updating (vs. `update`)
var ref$1 = el.__transferDomData
// (el)
var parentNode = ref$1.parentNode
var home = ref$1.home
var hasMovedOut = ref$1.hasMovedOut // recall where home is
if (!hasMovedOut && value) {
// remove from document and leave placeholder
// append to target
getTarget(value).appendChild(el)
el.__transferDomData = Object.assign({}, el.__transferDomData, { hasMovedOut: true, target: getTarget(value) }) } else if (hasMovedOut && value === false) {
// previously moved, coming back home
el.__transferDomData = Object.assign({}, el.__transferDomData, { hasMovedOut: false, target: getTarget(value) }) } else if (value) {
// already moved, going somewhere else
getTarget(value).appendChild(el)
}
},
unbind: function unbind (el, binding) {
el.className = place('v-transfer-dom', '')
if (el.__transferDomData && el.__transferDomData.hasMovedOut === true) {
el.__transferDomData.parentNode && el.__transferDomData.parentNode.appendChild(el)
}
el.__transferDomData = null
}
}
export default directive
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论