【问题标题】:TypeError: this.posts.filter is not a function using Vue js and wordpress apiTypeError:this.posts.filter 不是使用 Vue js 和 wordpress api 的函数
【发布时间】:2019-04-11 18:54:33
【问题描述】:

我正在尝试使用强大的 pro api 和 vue js 在 wordpress 中获取一些帖子。数据最初加载正确,但是,当我单击类别或在输入字段中键入内容时,我得到 TypeError: this.posts.filter is not a function。

在过滤后的函数中,我总是从 console.log("posts", this.posts[0]) 得到未定义的结果。

JS

var postList = Vue.extend({

    template: "#post-list-template",

    data: function(){
        return {
            posts:'',
            nameFilter:'',
            categories: '',
            categoryFilter: ''
        }
    },

    mounted: function(){

        var apiKey = 'my-api-key';

        this.$http.get('/wp-json/frm/v2/forms/10/entries', {
                headers: {
                    Authorization: 'Basic '+ btoa( apiKey +':x' )
                }
            })
            .then((response) => {
              this.posts = response.data;
            })

        //all category data

        this.$http.get('/wp-json/wp/v2/categories/')
            .then(response => this.categories = response.data);   
    },

    computed: {
        filteredPost: function () {

            var self = this;

            var selectedCategory = self.categoryFilter;

            console.log("selectedCategory", selectedCategory)
            console.log("posts", this.posts[0])

            if( selectedCategory === ""){

                return this.posts;

            }else{

                return this.posts.filter(function(post) {

                    return post.sqaja-value.indexOf(selectedCategory) >= 0;

                });

            }

            if( this.nameFilter == ''){
                return this.posts;
            }       

            var lowerCaseFilter = this.nameFilter.toLowerCase()

            return this.posts.filter(function(post){
                return post.meta.bl3pl.toLowerCase().indexOf(lowerCaseFilter) >= 0;

            });



        },

    } //computed
})

// Start a new instance of router (instead of router.map)
var router = new VueRouter({
  routes: [
    { path: '/', component: postList }
  ]
})


// Start a new instance of the Application required (instead of router.start)
new Vue({
  el: '#app',
  router: router,
  template: '<router-view></router-view>'
})

模板

<main class="wrap">
        <div id="app">
            <router-view></router-view>
        </div>
    </main>

    <template id="post-list-template">
        <div class="wrapper">
            <div class="container">
                <div class="row">
                    <h4>Filter by Title:&nbsp;</h4>
                    <input type="text" name="" v-model="nameFilter">

                    <h4>Filter by category</h4>
                    <div class="radio-wrap">
                        <input type="radio" value="" v-model="categoryFilter">
                        <label> All </label>
                    </div>

                    <div class="radio-wrap" v-for="category in categories" v-if="category.name != 'Uncategorized'">
                        <input type="radio" v-bind:value="category.id" v-model="categoryFilter">
                        <label> {{ category.name }} </label>
                    </div>

                </div>
            </div>
            <div class="container">
                <div class="row">
                    <div class="col-md-4" v-for="post in filteredPost">
                        <div class="card post">
                            <img class="card-img-top" v-bind:src="post.meta.xbxiv" >
                            <div class="card-body">
                                <h2 class="card-text">{{ post.meta.bl3pl }}</h2>
                                <small class="tags" v-for="category in post.cats">{{ category.name }}</small>
                            </div>
                        </div> <!-- .post -->
                    </div> <!-- .col-md-4 -->
                </div> <!-- .row -->
            </div> <!-- .container -->
        </div> <!-- .wrapper -->
    </template>

编辑 我不知道这是否相关,但代码适用于标准 wp api

[
    {
        "id": 15577,
        "date": "2018-09-10T23:30:43",
        "date_gmt": "2018-09-10T18:00:43",
        "guid": {
        "rendered": "https://example.com/?p=15577"
        },
        "modified": "2018-09-11T10:17:59",
        "modified_gmt": "2018-09-11T04:47:59",
        "slug": "demonetisation-and-its-impact-on-tax-collection-and-formalisation-of-the-economy",
        "status": "publish",
        "type": "post",
        "link": "https://example.com/demonetisation-and-its-impact-on-tax-collection-and-formalisation-of-the-economy/",
        "title": {
        "rendered": "Demonetisation and its impact on Tax collection and Formalisation of the Economy"
        },
        "content": {},
        "excerpt": {},
        "author": 6,
        "featured_media": 15576,
        "comment_status": "open",
        "ping_status": "open",
        "sticky": false,
        "template": "",
        "format": "standard",
        "meta": [],
        "categories": [],
        "tags": [],
        "_links": {}
    }
]

然而,强大的api看起来是这样的

{
    "y8rau": {
        "id": "5352",
        "item_key": "y8rau",
        "name": "",
        "ip": "::1",
        "meta": {},
        "form_id": "10",
        "post_id": "4862",
        "user_id": "1",
        "parent_item_id": "0",
        "is_draft": "0",
        "updated_by": "1",
        "created_at": "2016-11-25 02:46:33",
        "updated_at": "2018-02-21 10:08:58"
    },
    "o0nqn": {
        "id": "5353",
        "item_key": "o0nqn",
        "name": "",
        "ip": "::1",
        "meta": {},
        "form_id": "10",
        "post_id": "4863",
        "user_id": "1",
        "parent_item_id": "0",
        "is_draft": "0",
        "updated_by": "1",
        "created_at": "2016-11-25 02:46:34",
        "updated_at": "2018-02-21 09:41:57"
    }
}

【问题讨论】:

  • 当您尝试在mounted中分配this.posts时,您能否控制台记录response.data。
  • 是的,我可以在控制台中看到数据。我添加了一个编辑。你能看看,看看这是否有助于解决这个问题?感谢您的宝贵时间
  • 如果您在计算出的过滤后的帖子函数中尝试console.log("posts", self.posts[0]) 会怎样?
  • 这给了我“未定义”

标签: javascript wordpress vue.js


【解决方案1】:

那是因为您在初始化期间已将 posts 声明为空字符串。字符串原型没有filter 方法,因此会出错。

如果一开始将其声明为空数组,错误应该会消失:

data: function(){
    return {
        posts: [],
        nameFilter: '',
        categories: [],
        categoryFilter: ''
    }
},

p/s:我想categories 也应该是一个数组。

【讨论】:

  • 仍然出现同样的错误:[Vue warn]: Error in render: "TypeError: this.posts.filter is not a function"
  • 嗨,我添加了一个编辑。你能看看,看看这是否有助于解决这个问题?感谢您的宝贵时间
【解决方案2】:

好的,所以您收到了对您的 http 请求的响应,但它没有将该响应分配给“帖子”。这可能是由于 vue 的生命周期钩子是如何工作的。如果您将mounted() 更改为created(),它可能会起作用,但您也可以将“帖子”设为计算属性而不是数据元素。

为此,请从“数据”中删除帖子(和类别),这样您就剩下这些了。

data: function(){
  return {
    nameFilter:'',
    categoryFilter: ''
  }
},

然后将帖子(和类别)设为计算函数:

computed: {
  posts() {
    //put your $http.get request in here, but instead of assigning the response, return it
    .then((response) => {
      return response.data;
    })
  },
  categories() {
    //separate $http.get for categories and return response
  }
  // Then your other computed properties like filteredPosts
...
}

您可以使用 this.posts 访问其他计算函数中的帖子

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2021-11-23
    • 2021-09-18
    • 2021-07-14
    • 2021-01-14
    • 2020-04-26
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多