有一个 Vue-component
。
这是一个包含一些内容的 div
。
根据事件,此元素必须放置在给定坐标(相对于文档)。
我为它设置样式:
return {
position: "absolute",
top: `${x}px`,
left: `${y}px`,
};
但如果此元素的父元素之一具有 position: relative
则位置计算相对于父元素,而不是文档。
我的解决方案:将元素移动到文档根目录。
mounted() {
document.body.appendChild(this.$refs.container);
},
效果很好。 但我有疑问:
- 只用CSS能解决吗?
- 移动在Vue-template中渲染的元素会出现什么问题?
- 有更好的解决方案吗?
最佳答案
您拥有的是门户 的一个很好的用例。它允许组件存在于某个位置,但模板在其他地方呈现。看看portal-vue
Vue.config.productionTip = false;
Vue.use(PortalVue);
Vue.component('MyComponent', {
template: `
<div>
<h1>First</h1>
<portal to="destination">
<h1>Second</h1>
</portal>
</div>
`,
});
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/portal-vue@2.1.5/dist/portal-vue.umd.min.js"></script>
<div id="app">
<div class="portal-destination">
<portal-target name="destination"></portal-target>
</div>
<div><my-component></my-component></div>
</div>
关于css - 位置为 : absolute 的 Vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57096400/