简体   繁体   中英

vue.js making a data property = to the return value of a method

So im trying to assign this.clean = this.cleaner.

The results prop is an array of 20 objects that I want to filter. I want an array of objects that only have a valid poster_path value and to remove the ones that do not meet that requirement. Hence the .filter().

  props: ['results'],
  data() {
    return {
      clean: []
    }
  },
  mounted() {
    this.clean = this.cleaner
  },
  methods: {
    cleaner() {
      return this.results.filter(o => o.poster_path !== null)
    }
  }

Problem is using my vue devtool Vue doesnt seem to be saving the this.cleaner value. I get {"_custom":{"type":"function","display":"<span>ƒ</span> bound cleaner()"}} for the value of this.clean.

If I try to use a computed value I keep getting "(error during evaluation)" as the value of this.clean.

If i try this.clean = this.cleaner() it just saves an empty array.

Try this snippet. I think your code can be simplified down to this:

 const mockData = [ { name: 'abc', poster_path: 1 }, { name: 'def', poster_path: null } ] Vue.component('foo', { props: ['results'], template: '<ul><li v-for="c in clean" :key="index">{{c.name}}</li></ul>', computed: { clean: function() { return this.results ?this.results.filter(o => o.poster_path !== null) : []; } } }) var app = new Vue({ el: '#app', data() { return { results: mockData } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> Foo component: <foo :results="results"/> </div>

just assign the functionality of the funcion like this

props: ['results'],
data() {
  return {
   clean: []
  }
},
mounted() {
  this.clean = this.results.filter(o => o.poster_path !== null)
}    
props: ['results'],
data() {
  return {
    clean: this.results.filter(o => o.poster_path !== null)
  }
},

Please try it. You can directly import props to the component data.

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