Vue.js this is undefined inside computed property

大憨熊 提交于 2020-08-03 06:02:13

问题


I have following input tag with model selectedProp:

<input type="text" v-model="selectedProp" />

and I want to iterate through items like this:

<div v-for="item of filteredItems">{{item.prop}}</div> 

Here's the script for the component:

export default {
  name: 'App',
  data() {
    return {
      items: [],
      selectedProp: "",
      projects: [],
      errors: []
    }
  },
  created() {
   axios.get(`${URL}`)
   .then(response => {
      // JSON responses are automatically parsed.
      this.items = response.data;
    })
    .catch(e => {
      this.errors.push(e)
    });

  },

  computed: {
    filteredItems() {
      if(this.selectedProp) {
        console.log(this.selectedProp);
        return this.items.filter(function (item) {
          return item.prop == this.selectedProp;
        });

      }
      return this.items;

    }
  },
}

Error

this is undefined inside computed property


回答1:


In this case you could use arrow function which has access to this object

 return this.items.filter( (item)=> {
      return item.prop == this.selectedProp;
    })


来源:https://stackoverflow.com/questions/52797842/vue-js-this-is-undefined-inside-computed-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!