1

I have an array of objects which contain data, I am displaying each object using v-for. When clicking on each object it have to display the name of object, for this on clicking object I had made a method with id as argument so it can display only particular targeted id data, but the name property which I made empty on default it is showing error of undefined property in method of Vue.js, Why I am getting this error?

Html Code

Here the serviceList is an array of objects and serviceBox(s.id) is method I used

<ul>            
   <li v-for="s in serviceList" v-on:click="serviceBox(s.id)">{{s.mKey}}</li>
</ul>

<p>The Service Name is :{{fService}}</p>

{{fService}} is the property which I needed to display name

JS Code

<script>
   export default {
     name: 'app',
     data () {
       return {
         fService: '', 
       }
     },

    serviceBox(id){
       this.serviceList.forEach(function(s) { 
          if(id == s.id){
            this.fService = s.service;
             //here i am getting error cannot set property 'fService' of undefined
          }
       })
    },
 }
gil
  • 1,318
  • 12
  • 19
nani raju
  • 85
  • 1
  • 11

1 Answers1

1

Just set the fService data property directly in the click.

console.clear()

new Vue({
  el: "#app",
  data:{
    serviceList: [
      {id: 1, mKey:1, service: "service 1"},
      {id: 2, mKey:2, service: "service 2"},
      {id: 3, mKey:3, service: "service 3"},
      {id: 4, mKey:4, service: "service 4"},
    ],
    fService: null
  }
})
li {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
    <ul>            
        <li v-for="s in serviceList" v-on:click="fService = s.service">{{s.mKey}}</li>
    </ul>
    <p>The Service Name is :{{fService}}</p>
</div>

If you don't want to do that in the template, you could also pass the service to a method and set fService to the passed service.

Bert
  • 80,741
  • 17
  • 199
  • 164
  • But why this.fService property not worked through a method – nani raju Aug 09 '18 at 14:49
  • @naniraju Your `forEach` callback creates a new scope because you used a regular function (`function () {...}`) which means that `this` is not the Vue. [See this question for more detail](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback). – Bert Aug 09 '18 at 14:52