简体   繁体   中英

Vue.js this is undefined inside computed property

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM