javascript - 如何在嵌套循环中使用v-for?

标签 javascript vuejs2 wordpress-rest-api

我正在尝试使用使用来自 Wordpress REST API 的数据对象的 VueJs2 框架来过滤 JSON 对象(在我的示例中该对象名为“post”)。我有与我的帖子关联的嵌套数组(元数据标签),当用户在我的输入元素中键入搜索查询时,我想对其进行过滤/搜索:

<强> JSFIDDLE link

HTML:

<div id="app" class="container" style="padding-top: 2em;">      
  <input v-model="searchText">

  <table class="table table-striped" v-if="posts">
    <thead>
      <tr>
        <th>Title</th>
        <th>Product Type</th>
      </tr>
    </thead>
    <tr v-for="post in itemsSearched">
        <td>{{post.title.rendered}}</td>
        <!-- this part is probably not correct -->
        <td v-for="post._embedded['wp:term'][1] in itemsSearched"></td>
    </tr>
  </table>
</div>

JS:

var vm = new Vue({
  el: '#app',
  data: {
    message: 'hello world',
    searchText: '',
    posts: []
  },
  computed : {
    itemsSearched : function(){
      var self = this;
      if( this.searchText == ''){
        return this.posts;
      } 
      return this.posts.filter(function(post){
        return post.title.rendered.indexOf(self.searchText) >= 0;
        //what to put here to filter the tags ??
      });
    }
  },
  created: function(){
    $.get('https://wordpress-dosstx.c9users.io/wp-json/wp/v2/products/' + '?_embed=true')
      .done(function(data) {
        vm.posts = data;
      });
  }
});

如果您可以提供一些有关如何进行的建议,那就太好了。谢谢。

最佳答案

我更新了您的fiddle 。您需要循环遍历数组的项而不是整个搜索到的数组。

<div id="app" class="container" style="padding-top: 2em;">      
  <input v-model="searchText">

  <table class="table table-striped" v-if="posts">
    <thead>
      <tr>
        <th>Title</th>
        <th>Product Type</th>
        <th>Tags</th>
      </tr>
    </thead>
    <tr v-for="post in itemsSearched">
      <td>
        <a :href="post.link" target="_blank">
          <img :src="post._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.source_url"
             style="width:75px;height:75px;"/>
        </a>
      </td>
      <td>
        <a :href="post.link" target="_blank" v-html="post.title.rendered"></a><br/>
        <div v-html="post.content.rendered"></div>
      </td>
      <td v-for="item in post._embedded['wp:term']">
        <div v-for="subItem in item">
          <a :href="subItem.link">{{subItem.name}}</a>
        </div>
      </td>
    </tr>
  </table>
</div>

关于javascript - 如何在嵌套循环中使用v-for?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44828226/

相关文章:

java - 如何修复“Volley : [15771] BasicNetwork. performRequest : Unexpected response code 404 in android?

javascript - 如何在 Gutenberg 中使用序列化数据?

javascript - 如何使用ajax为输入添加值

javascript - 为什么 splice 在 angular js 中不能正常工作

javascript - 使用 Node 和 Angular 从 Last.fm API 获取搜索结果

javascript - 如何在 vue-router 中设置 afterEach 处理程序

javascript - vue.js carousel-3d 不显示数据

css - 删除 v-layout 中的元素空白 [Vue + Vuetify]

javascript - meteor :图像的预加载

javascript - 使用 Wordpress REST api 创建帖子时如何设置自定义元值