简体   繁体   中英

Push to an array from with in a computed property in Vue.js 2

I am looking to push to an array from with in a computed property in Vue.js 2, Vue is being used within Laravel and I am getting the following response.

createSelection:"(error during evaluation)"

The following code is being used:

<template>
  <div>
    <div>Credits carried through: {{ credits }}</div>
    <div v-for="meal in meals">
      {{meal}}
      <input :id="meal" :name="meal" v-model.number="creditsPerMeal[meal]" type="number">
    </div>
    <div>
      Credits used: {{creditsSum}}/{{credits}}
    </div>
  </div>
</template>

<script>
  export default {

    mounted() {
        console.log('Component ready.');

        console.log(JSON.parse(this.f));

    },

    props: ['f','c'],

    name: 'credits',
    data: function () {
     var meals = JSON.parse(this.f)

     var creditsPerMeal = {}
     for (var i = 0; i < meals.length; i++) {
       creditsPerMeal[meals[i]] = 0
     }

     var createSelection = []


      return {
        credits: this.c,
        meals,
        creditsPerMeal
      }
    },

    computed: {
      creditsSum () {
        return Object.values(this.creditsPerMeal).reduce((a, b) => a + b, 0)
      },

      createSelection: function (){
        for (var i = 0; i < meals.length; i++) {
           createSelection.push({
              food: meals[i],
              quantity: creditsPerMeal[meals[i]]
            })
          }
      }
    }
  }
</script>

Computed method should return something and actually they should not do anything, just compute something and return. Your computed method has no return at all. First of all move your push logic to method:

   computed: {
      creditsSum () {
        return Object.values(this.creditsPerMeal).reduce((a, b) => a + b, 0)
      },
   },
   methods: {
      createSelection (){
          for (var i = 0; i < meals.length; i++) {
              createSelection.push({
                 food: meals[i],
                 quantity: creditsPerMeal[meals[i]]
              })
          }
      }
   }

Also error during evaluation is not description of problem and not looks like Vue problem, may be you can provide more detailed error?

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