【发布时间】:2021-04-22 06:21:39
【问题描述】:
我正在使用 vue 和 popperjs 制作一个下拉组件。要知道我正在使用vuejs v.2.6.12 和popperjs v.2.9.2,这是代码
<template>
<button type="button" @click="show = true">
<slot />
<portal v-if="show" to="dropdown">
<div>
<div
style="position: fixed; top: 0; right: 0; left: 0; bottom: 0; z-index: 99998; background: black; opacity: .2"
@click="show = false"
/>
<div
ref="dropdown"
style="position: absolute; z-index: 99999;"
@click.stop="show = autoClose ? false : true"
>
<slot name="dropdown" />
</div>
</div>
</portal>
</button>
</template>
<script>
import { createPopper } from "@popperjs/core";
export default {
props: {
placement: {
type: String,
default: "bottom-end"
},
boundary: {
type: String,
default: "scrollParent"
},
autoClose: {
type: Boolean,
default: true
}
},
data() {
return {
show: false
};
},
watch: {
show(show) {
if (show) {
this.$nextTick(() => {
this.popper = createPopper(this.$el, this.$refs.dropdown, {
placement: this.placement,
modifiers: [
{
name: "preventOverflow",
options: {
boundary: this.boundary
}
}
]
});
});
} else if (this.popper) {
setTimeout(() => this.popper.destroy(), 100);
}
}
},
mounted() {
document.addEventListener("keydown", e => {
if (e.keyCode === 27) {
this.show = false;
}
});
}
};
</script>
当我尝试运行代码时,我收到错误消息Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.
我不知道为什么会出现此错误,我想我已将参考 this.$el 和 popper this.$refs.dropdown 放在正确的位置。
有人可以帮我解决这个问题吗?
谢谢你
【问题讨论】:
-
在安装组件之前,
this.$el和this.$refs.dropdown都不存在。观察者是否在挂载前被触发? -
@ChaseIngebritson 是的
-
this.$refs.dropdown的值是多少?您是否尝试过不使用portal-vue?
标签: javascript vue.js popperjs vue-portal