【问题标题】:Accessing properties of iterated values in Vue.js在 Vue.js 中访问迭代值的属性
【发布时间】:2016-11-28 18:28:23
【问题描述】:

我正在像这样遍历一个列表:

  <li v-for="item in filteredParentItems"
      v-if="item.action === 'list'"
      v-on:click="getNextPath"
      v-bind:data-next-path="item.nextPath"
      v-bind:data-action="item.action"
      v-bind:class="{ active: isActive }"
      class="item">
        {{item.name}}
        <i class="fa fa-arrow-right" aria-hidden="true"></i>
  </li>

为了判断项目是否处于活动状态,我运行 isActive,这是一个计算函数,用于判断路径是否等于我在 Vuex 商店中的面包屑路径:

  computed: {
    isActive () {
      return this.nextPath === this.$store.state._breadcrumbPath;
    }
  }

问题是我无法访问计算函数中的 item.nextPath,因为我没有将 li 设置为自己的组件。有没有办法将实际项目传递给 isActive 函数以获取其属性?

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    我不相信有办法将值传递给计算属性。相反,您可以将isActive 更改为一个方法,然后传入item

    li

    v-bind:class="{ active: isActive(item) }"
    

    然后将isActive改成一个方法,对具体的item进行操作:

    methods: {
      isActive (item) {
        return item.nextPath === this.$store.state._breadcrumbPath;
      }
    }
    

    【讨论】:

    • 我现在要试一试。
    【解决方案2】:

    您需要在类绑定中执行此操作:

    <li v-for="item in filteredParentItems"
      v-if="item.action === 'list'"
      v-on:click="getNextPath"
      v-bind:data-next-path="item.nextPath"
      v-bind:data-action="item.action"
      v-bind:class="{ active: item.nextPath === _breadcrumbPath }"
      class="item">
        {{item.name}}
        <i class="fa fa-arrow-right" aria-hidden="true"></i>
    </li>
    

    然后在您的组件脚本中:

    computed: {
    
      _breadcrumbPath () {
        this.$store.state._breadcrumbPath
      },
      ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 2013-12-23
      • 2016-09-05
      • 2021-11-07
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多