简体   繁体   中英

computed property not returning correct value in Vue.js

I have a Vue.js project where uses can select an item (an app) from a select input element. It uses an apps array that is specified in the data section. All of that is working correctly.

    <div class="large-8 columns" v-if="selectedAppId">
      {{selectedApp.name}}
    </div>
    <div class="large-8 columns" v-else>
      <select v-model="selectedAppId" name="timeline_event[site_id]">
        <option value=null>Select One</option>
        <option v-for="app in apps" :value="app.id" :key="app.id">{{app.name}}</option>
      </select>
    </div>
  </div>

I'd like to be able to return the selectedApp from the apps array and output the name as seen in the first part of the conditional above.

I'm not sure if a computed property is the correct way to do this - I have also tried as a method and that was problematic. In the following, the correct app is selected from the apps array but rather than rendering out the selectedApp.name , I get an error stating "Cannot read property 'name' of undefined".

In my console.log, it is outputting an ob Observer. I am obviously not doing this correctly. What would be the correct way to do this?

  computed: {
    selectedApp(){
      console.log('here is selectedAppId ' + this.selectedAppId)
      this.apps.forEach((app) => {
        if(app.id == this.selectedAppId){
          console.log('a hit');
          console.log(app)
          return app
        }else{
          console.log('a miss');
        }
      })
    },
  },

I think you don't need a forEach loop but just find the match between your selectedAppId (which is fill with the app.id ) and the app

 new Vue({ el: "#app", data() { return { selectedAppId: '', apps: [{ id: 1, name: "App1" }, { id:2, name: "App2" }, { id: 3, name: "App3" }] } }, computed: { selectedApp(){ return this.apps.find(app => app.id == this.selectedAppId ) } } }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script> <div id="app"> <div class="large-8 columns" v-if="selectedAppId"> {{ selectedApp.name }} </div> <div class="large-8 columns" v-else> <select v-model="selectedAppId" name="timeline_event[site_id]"> <option value=null>Select One</option> <option v-for="app in apps" :value="app.id" :key="app.id">{{app.name}}</option> </select> </div> </div> 

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