如何在嵌套在方法下的for reach循环中访问和设置vue.js的属性

how to access and set property of vue.js in for reach loop which nested under methods

我有一个包含数据的对象数组,我正在使用 v-for 显示每个对象。当点击每个对象时,它必须显示对象的名称,对于这个点击对象,我制作了一个 methodid 作为参数,因此它只能显示特定的目标 id 数据,但是名称 属性 我在默认情况下设为空它在 Vue.js 的方法中显示未定义 属性 的错误,为什么我会收到此错误?

Html代码

这里的serviceList是对象数组,serviceBox(s.id)是方法 我用了

<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}} 是我需要显示名称

的 属性

JS代码

<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
          }
       })
    },
 }

点击直接设置fService数据属性即可

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>

如果您不想在模板中这样做,您也可以将服务传递给方法并将 fService 设置为传递的服务。