vue.js:切换方法更改值,但视图中没有更改任何行为

时间:2017-06-29 12:46:05

标签: javascript css vue.js vuejs2

如果我点击其中一个列表(满足切换功能条件),那么它应该显示或不显示下拉菜单。到目前为止,方法切换更改了chrome控制台内dropDownOpen的值,但视图中没有显示任何更改,代码:

控制台显示值已更改,并且未在模板中更改!

 <ul>
          <li v-for="(navHeading, index) in headerMenuItems" @click="toggle(navHeading.name)" :class="{'open': dropDownOpen}">
            <icon :glyph="navMenuIconNames[index]" :viewBox="navMenuIconNames[index].viewBox" :height="25" :width="50"></icon>
            <a class="navigation-title" href="#">{{ navHeading.name }}</a>
            <ul class="drop-down-menu">
              <li v-for="dropDownMenuItem in navHeading.children">
                <a class="drop-down-menu-item-title">{{ dropDownMenuItem.name }}</a>
              </li>
            </ul>
          </li>
</ul>

脚本:

 data() {

      const dropDownOpen = false
      return { dropDownOpen }
    },
methods: {
      toggle: (dropDownName) => {
        if (dropDownName === 'Meer') {
          this.dropDownOpen = !this.dropDownOpen
        }
        console.log(this.dropDownOpen)
        return this.dropDownOpen
      }
    }

CSS:

<style scoped>
  .open .drop-down-menu {
    display: block;
    background-color: tomato;
  }

  .drop-down-menu {
    display: none;
  }
</style>

2 个答案:

答案 0 :(得分:2)

你的方法中的

this没有指向vue实例,所以使用普通函数而不是胖箭头函数

methods: {
  toggle: function(dropDownName) {
    if (dropDownName === 'Meer') {
      this.dropDownOpen = !this.dropDownOpen
    }
    console.log(this.dropDownOpen)
    return this.dropDownOpen
  }

请参阅warning为什么不应将=>箭头函数与方法

一起使用

在模板中添加v-show这样的属性。

<ul v-show="dropDownOpen" class="drop-down-menu">

答案 1 :(得分:0)

不确切知道,但这有效:

 methods: {
      toggle(dropDownName) {
        if (dropDownName === 'Meer') {
          this.dropDownOpen = !this.dropDownOpen
        }
        return this.dropDownOpen
      }
    },

和模板:

 <ul>
      <li v-for="(navHeading, index) in headerMenuItems" @click="toggle(navHeading.name)">
        <icon :glyph="navMenuIconNames[index]" :viewBox="navMenuIconNames[index].viewBox" :height="25" :width="50"></icon>
        <span>{{ dropDownOpen }}</span>
        <a class="navigation-title" href="#">{{ navHeading.name }}</a>
        <ul v-show="dropDownOpen" class="drop-down-menu">
          <li v-for="dropDownMenuItem in navHeading.children">
            <a class="drop-down-menu-item-title">{{ dropDownMenuItem.name }}</a>
          </li>
        </ul>
      </li>
 </ul>