悬停嵌套Vue组件

时间:2020-02-09 19:03:13

标签: javascript vue.js

我有一个嵌套和重复使用的vue组件。我正在尝试使用v-show悬停其外部父项时显示部分组件(图标)。为此,我将父级和子级索引作为道具传递,但是当子元素悬停时,我的父元素对于v-show返回true。我该怎么解决?

<div v-for="course, index in courses">

  <!-- hover me -->
  <div class="header" @mouseover="setShowIndex(index)" @mouseout="resetShowIndex">

  <!-- part of this component should v-show when its parent is hovered -->
  <MyCustomComponent
     type="course"
     :showCourseIndex="showCourseIndex"
  />

  <!-- items.lessons can be hovered too, but the parent should not v-show when this is hovered -->
  <div 
    v-for="lesson, i in course.lessons"
    @mouseover="setShowIndex(index, i)" 
    @mouseout="resetShowIndex"
  >
    <MyCustomComponent
       type="lesson"
       :showCourseIndex="showCourseIndex"
       :showLessonIndex="showLessonIndex"
    />
  </div>
</div


/** 
 * update indexes to pass as props
 */
setShowIndex(index, i) {
  if (i !== undefined) {
      this.showLessonIndex = i;
  }
  this.showCourseIndex = index;
},

resetShowIndex() {
  this.showCourseIndex = null;
  this.showLessonIndex = null;
}

// MyCustomComponent

<div>
  <!-- ... more -->
  <div v-show="shouldShowIndex">
    <p>Show me</p>
  </div>
  <!-- ... more -->
</div>


computed: {

    shouldShowIndex() {

      if ( this.type == 'lesson'
        && this.showModuleIndex == this.moduleIndex 
        && this.showLessonIndex == this.lessonIndex ) {

        return true;

      } else if (this.type == 'course' && this.showModuleIndex == this.moduleIndex ) {

        return true; // problem here, this is returning True when a lesson is hovered

      }

      return false;
    },

}

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则如果标头悬停,则标题应显示其图标;如果悬停,则课程应显示其图标,但不会触发标头。

setShowIndex(index, i) {
  if (i !== undefined) {
      this.showLessonIndex = i;
  } else {
      this.showCourseIndex = index;
  }
},

您只需要一个吗?