javascript - VueJS 过滤器在 v-for 中不起作用

标签 javascript vuejs2 axios

我在 VueJS 上遇到一个错误,在 Axios 响应的 v-for 中添加了一个过滤器,我不明白如何解决它。如果我在 value 变量上生成了 console.log,过滤器 set_marked 会返回一个 undefined 值。

这是 HTML:

<main id="app">
  <div v-for="item in productList" :key="item.id">
  <header>
    <h2>{{ item.title }}</h2>
  </header>
  <article class="product-card">
      {{ item.content | set_marked  }}
  </article>
  </div>
</main>

和 Javascript:

var app = new Vue({
  el: '#app',
  data: {
    loading: false,
    loaded: false,
    productList: []
  },
  created: function() {
    this.loading = true;
    this.getPostsViaREST();
  },
  filters: {
    set_marked: function(value) {
      return marked(value);
    }
  },
  methods: {
    getPostsViaREST: function() {
      axios.get("https://cdn.contentful.com/spaces/itrxz5hv6y21/environments/master/entries/1Lv0RTu6v60uwu0w2g2ggM?access_token=a2db6d0bc4221793fc97ff393e541f39db5a65002beef0061adc607ae959abde")
           .then(response => {
              this.productList = response.data;
            });
    }
  }
})

你也可以在我的codepen上试试: https://codepen.io/bhenbe/pen/deYRpg/

感谢您的帮助!

最佳答案

您正在 productList 上使用 v-for 进行迭代,但在您的代码中 productList 不是一个数组而是一个对象(字典也就是说)。事实上,如果你看它,它有这样的结构:

{
    "sys": {
        "space": {
            "sys": {
                "type": "Link",
                "linkType": "Space",
                "id": "itrxz5hv6y21"
            }
        },
        "id": "1Lv0RTu6v60uwu0w2g2ggM",
        "type": "Entry",
        "createdAt": "2017-01-22T18:24:49.677Z",
        "updatedAt": "2017-01-22T18:24:49.677Z",
        "environment": {
            "sys": {
                "id": "master",
                "type": "Link",
                "linkType": "Environment"
            }
        },
        "revision": 1,
        "contentType": {
            "sys": {
                "type": "Link",
                "linkType": "ContentType",
                "id": "page"
            }
        },
        "locale": "fr-BE"
    },
    "fields": {
        "title": "Retour sur douze années de design",
        "content": "Douze années ... vie."
    }
}

遍历它,在第一次迭代时将 "sys" 键的值分配给 item,即:

{
    "space": {
        "sys": {
            "type": "Link",
            "linkType": "Space",
            "id": "itrxz5hv6y21"
        }
    },
    "id": "1Lv0RTu6v60uwu0w2g2ggM",
    "type": "Entry",
    ...
    "locale": "fr-BE"
},

在第二次迭代中 "fields" 键的值,其值为:

{
    "title": "Retour sur douze années de design",
    "content": "Douze années ... vie."
}

由于您正在访问 item.titleitem.content,因此 titlecontent 键不是出现在第一个对象中,但仅出现在第二个对象中,在第一次迭代中它们将是 undefined。因此,在第一次迭代中,您将 undefined 作为 item.content 的值传递给 set_marked 过滤器。

productList 是对 GET 请求的响应,正如我们所见,它返回的不是数组而是对象。

如果您向过滤器添加检查 if (!value) return ''; 它会起作用,但您只是隐藏了 API 返回的内容与您返回的内容之间的差异问题期待。

如果您通过过滤 result.data 的子对象并仅保留包含 titlecontents 字段,它有效:

function marked(value) {
    return value.toUpperCase();
}

var app = new Vue({
  el: '#app',
  data: {
    productList: []
  },
  created: function() {
    this.loading = true;
    this.getPostsViaREST();
  },
  filters: {
    set_marked: function(value) {
      // console.log(value);
      return marked(value);
    }
  },
  methods: {
    getPostsViaREST: function() {
        axios.get("https://cdn.contentful.com/spaces/itrxz5hv6y21/environments/master/entries/1Lv0RTu6v60uwu0w2g2ggM?access_token=a2db6d0bc4221793fc97ff393e541f39db5a65002beef0061adc607ae959abde")
           .then(response => {
              // this.productList = response.data;
              let data = response.data;
              let productList = [], key;
              for (key in data) {
                let val = data[key];
                if ((val.title !== undefined) && (val.content !== undefined)) {
                  productList.push(val);
                }
              }
              this.productList = productList;
            });
    }
  }
})
@import url('https://fonts.googleapis.com/css?family=Lato');

body{
  font-family: 'Lato', sans-serif;
  font-size: 1.125rem;
}

#app > div{
  max-width: 68ch;
  margin: 0 auto;
}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<main id="app">
  <div v-for="item in productList" :key="item.id">
  <header>
    <h1>{{ item.title }}</h1>
  </header>
  <article class="product-card" v-html="$options.filters.set_marked(item.content)"></article>
  </div>
</main>

关于javascript - VueJS 过滤器在 v-for 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49975782/

相关文章:

javascript - 为什么是 "if(!!variable)"而不是 "if(variable)"?

javascript - 我目前正在使用 Axios 对 JSON 文件发出 3 个 GET 请求,它们是同时加载还是一个接一个加载?

javascript - axios请求后如何显示item名称

javascript - 符号: Well Known Symbols to Change Built-In Behavior

javascript - Mongodb 和 Espress : store a object in a model

javascript - 访问asp :CheckBox inner input from jQuery

javascript - 更新 Vuetify slider 上的值

javascript - 如何防止选择表单被更改,直到 Vue 中的对话框完成

javascript - 如何使用 React 和 AXIOS 创建全局 Handler?

javascript - 无法读取我的 API 或特定 API [React.js/Node.js/Axios/Fetch]