在VUEJS中单击组件中的按钮后,如何将类添加到主体中



我正在设计一个具有不同模态的库(当然还有Overlay(。当modal打开时,我仍然可以滚动下面的内容。我想以某种方式将overflow:hidden用于body元素,而不需要通过我的模态组件来操纵DOM。

请和我分享你的想法!

在Vue组件中添加一个方法,该方法创建覆盖并向主体添加一个不可滚动的类。

/**
* Create the viewport overlay.
*/
createOverlay() {
this.overlay = document.createElement('div')
this.overlay.className = 'overlay'
this.overlay.addEventListener('click', () => this.close())
document.body.appendChild(this.overlay)
document.body.classList.add('no-scrollable')
}
/**
* Close the Modal when overlay is clicked.
*/
close() {
// Trigger Modal Close Here
this.overlay.removeEventListener('click', this.removeOverlay())
}
/**
* Remove the overlay from the DOM.
*/
removeOverlay() {
document.body.removeChild(this.overlay)
document.body.classList.remove('no-scrollable')
}

CSS样式:

.overlay {
background: rgba(0, 0, 0, 0.6);
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: 1040;
}
body.no-scrollable {
overflow: hidden;
}

您可以做的是绑定类,使其动态如下:<h1 :class="{ active: hello }">Show</h1>"active"是一个可以根据需要设置样式的类,"hello"只是一个可以设置为false的属性,然后您可以切换,或者在<button @click="hello = true">Hide title</button>这样的按钮中更改为false,以防您想切换使用<button @click="hello =! hello">Hide title</button>

`:class="{ active: hello }"` the way it works is that active is only going to be valid if the value you pass after the `:` is true. 

我在这里留下了一个链接到sandbox.io,这样你就可以看到一个例子:

https://codesandbox.io/s/confident-sun-h4ur9

我发现我可以使用根元素而不是主体元素!我可以解决滚动模式背景的问题,如下所示:

<button @click="modalShow">Show Modal</button>
modalShow() {
// Trigger Modal Open Here
this.showModal = true;
this.$root.$el.classList.add('show-modal');
}
close() {
// Trigger Modal Close Here
this.showModal = false;
this.$root.$el.classList.remove('show-modal');
}

对于Css样式:

.show-modal {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
}

这解决了我的问题。我希望它也能帮助你们:(

最新更新