【问题标题】:VueJS filter doesn't work in v-forVueJS 过滤器在 v-for 中不起作用
【发布时间】:2018-04-23 07:42:04
【问题描述】:

我在 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/

感谢您的帮助!

【问题讨论】:

  • 什么是marked函数?
  • 这是我添加的另一个库以显示降价内容:github.com/markedjs/marked
  • 那么为什么不将它包含在演示中呢?
  • 这似乎不是问题。我的错误发生在标记的函数调用之前。

标签: javascript vuejs2 axios


【解决方案1】:

您在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."
    }
}

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

{
    "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 字段的子对象,将productList 构建为数组,则它可以工作:

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>

【讨论】:

  • 我刚刚找到了这段代码,但我很失望。我不知道为什么没有这段代码: if (!value) return '';值 = value.toString();该值未定义...最后一个问题是html被转义...
  • productList 中的一些 item 记录可能缺少 content 字段。使用开发工具检查来自GET 请求的响应。
【解决方案2】:

好的,我在文档中找到了解决方案。

我必须将以下代码添加到过滤器 set_marked 才能正常工作:

if (!value) return '';
value = value.toString();

我目前不知道为什么需要这些额外的行。

我遇到了第二个问题,因为返回的 html 被 VueJS 转义了。 避免此问题的最简单方法是使用 v-html 指令。 要在 v-html 指令中应用过滤器,您必须使用以下语法:

v-html="$options.filters.set_marked(item.content)"

你可以在这里找到我的笔:https://codepen.io/bhenbe/pen/deYRpg

【讨论】:

  • 第一部分不是解决您的问题的实际方法:这些行只是防止空值/未定义值和非字符串值,但您只是在规避实际问题,即您期望 v-for 中的数组与 response.data 的对象性质之间的不匹配
  • 对不起,我不明白你的回答。过滤器返回值变量的“未定义”值,作为过滤器的参数传递。如果我添加我在答案中指定的两行,则 value 返回正确的字符串。这就像一个临时结果,我真的不明白为什么......我在codepen中添加了两个console.log。如果您查看控制台,第一个结果返回“未定义”,第二次返回值太长的错误消息。如果您能帮助理解它为什么会这样工作,我非常感谢您的反馈!
  • 是的,它返回undefined,原因我在下面的回答中解释了。我会尝试修改它并以更清晰的方式解释问题。
【解决方案3】:

通常我只是在需要过滤时创建一个方法,然后在需要时在我的组件中使用它。

即:

    methods: {
    getPostsViaREST: function() {
      axios.get("https://cdn.contentful.com/spaces/itrxz5hv6y21/environments/master/entries/1Lv0RTu6v60uwu0w2g2ggM?access_token=a2db6d0bc4221793fc97ff393e541f39db5a65002beef0061adc607ae959abde")
           .then(response => {
              this.productList = response.data;
            });
    },
    filterPost(post) {
     return _.toUpper(post);
    }
  }

然后在你的组件中:

 <h1>{{ filterPost(item.title) }}</h1>

在这里找到完整的例子:

https://codepen.io/Venomzzz/pen/mLrQVm?editors=1011

【讨论】:

  • 感谢您的回答。如果我添加一个console.log,过滤器和方法似乎被调用了两次。我将在 VueJS 的过程中进一步了解原因。
  • 您能详细说明一下吗?这不是“过滤器”,我只是在方法前加上过滤器,如果这看起来令人困惑,请道歉。
  • 不抱歉,你的例子很清楚。我不明白的是,如果我将 console.log 添加到您的 filterPost 方法,我看到它被调用了两次。一次未定义,第二次具有良好的变量值。我在 vuejs 的过程中看不到为什么以及在哪里解释,所以我对结果感到失望
猜你喜欢
  • 2018-01-04
  • 1970-01-01
  • 2018-12-20
  • 2020-08-06
  • 1970-01-01
  • 2019-05-07
  • 2019-01-31
  • 2020-10-21
  • 2017-09-20
相关资源
最近更新 更多