我显示了一个从子组件单击的div。在任何类型的循环之外,组件都会在页面上呈现多次。当我在组件的这个特定实例中显示div时,我希望将其隐藏在所有其他实例中。我曾尝试使用ref关闭所有具有DOM操作的实例,但不起作用。
<template>
<span>
<div class="options--small" @click="toggleOptions" />
<div v-show="showOptions" ref="test" class="options-menu">
<slot />
</div>
</span>
</template>
<script>
export default {
name: 'ShowOptions',
data () {
return {
showOptions: false
}
},
methods: {
toggleOptions () {
this.$refs.test.style.display = 'none'
this.showOptions = !this.showOptions
}
}
}
</script>发布于 2021-06-02 05:19:28
您绝对不应该使用ref或直接访问DOM;这始终是最后的手段。
每个选项菜单的可见性由相应组件的showOptions属性控制。您需要一种方法来向每个组件实例传达您希望它们隐藏菜单的信息。这可以通过使用事件总线来实现。通常,为每个Vue项目都有一个这样的实现是个好主意,这样您就可以执行解耦的组件间通信。
如果您使用的是Vue 2,那么Vue实例可以用作事件总线。
未经测试:
// event-bus.js
const v = new Vue()
export function on(event, fn) {
v.$on(event, fn)
}
export function off(event, fn) {
v.$off(event, fn)
}
export function emit(event, ...args) {
v.$emit(event, ...args)
}import * as bus from './event-bus.js'
export default {
data() {
return {
showOptions: false
}
},
created() {
bus.on('ShowOptions.hide', this.onShowOptionsHide)
},
destroyed() {
// Important otherwise leaks memory
bus.off('ShowOptions.hide', this.onShowOptionsHide)
},
methods: {
onShowOptionsHide() {
// Hide our options menu when other menu shows theirs
this.showOptions = false
},
toggleOptions() {
if (this.showOptions) {
this.showOptions = false
} else {
// Tell other components to hide their options menu
bus.emit('ShowOptions.hide')
this.showOptions = true
}
}
}
}如果你不想使用事件总线,那么你可以跟踪每个组件实例,以便隐藏它们的菜单。
未经测试:
const instances = new Set()
export default {
data () {
return {
showOptions: false
}
},
created() {
instances.add(this)
},
destroyed() {
instances.delete(this)
},
methods: {
hideOtherMenus() {
for (const i of instances) {
if (i !== this) {
i.showOptions = false
}
}
},
toggleOptions() {
this.hideOtherMenus()
this.showOptions = !this.showOptions
}
}
}https://stackoverflow.com/questions/67795427
复制相似问题