【问题标题】:Call function on v-data-table item在 v-data-table 项目上调用函数
【发布时间】:2020-05-11 08:38:44
【问题描述】:

假设我有一个对象列表:

[teacher {
   name: '',
   department: 'this is department id',
   .......
   .......
}]

我有部门作为另一个对象:

[department {
  id: '',
  name: '',
  ......
  .....
  }]

我已经为部门实现了getter:

state: {
    departments: [],
  },
  getters: {
    getDepartmentById: (state) => (id) => {
        return state.departments.find(d => d.id == id)
      }
  },

我正在使用 vuetify v-data-table 来渲染项目。现在如何调用getDepartmentById 函数在教师列表中加载部门名称。我想显示部门名称是教师列表,现在我有部门 ID。

【问题讨论】:

  • 你的header数据有没有放到vue数据模型中?

标签: vue.js vue-component vuex vuetify.js


【解决方案1】:

您可以将这段代码用于模板:

<template>
  <v-data-table
    :headers="headers"
    :items="teachers"
    :items-per-page="5"
    class="elevation-1"
  ></v-data-table>
</template>

脚本的这段代码:

data: () => ({
    headers: [
      {
        text: 'Teacher',
        value: 'name' // Must contain this attribute in each teacher
      },
      {
        text: 'Teacher',
        value: 'departmentName' // Must contain this attribute in each teacher
      }
    ],
    teachers: [
    ]
}),
methods: {
    created: async() => {
        const teachersJson = await fetch(...) // call to an API
        this.teachers = teachersJson
                           .map(teacher => 
                             ({ 
                               ...teacher, // Association, same as Object.assign
                               departmentName: this.getDepartmentName(teacher.department)
                             })
                           )
    },
    getDepartmentName: (id) => {
        const department = this.$store.state.departmentsStore.findById(id)
        return department && departname.name
    }
}

【讨论】:

  • 我正在使用axios调用api。在created 钩子上我调用const teacherJson = this.get_teacher_list()get_teacher_list 是使用mapActionvuex 映射的操作,并按照您上面的代码完成。但我在控制台中收到teacherJson.map is not a function 错误。
  • 这是因为一个动作没有返回,你必须将调用关联到一个状态变量,然后创建一个getter来访问它的值
猜你喜欢
  • 2021-04-23
  • 2020-05-14
  • 2020-03-02
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 2020-04-09
  • 1970-01-01
相关资源
最近更新 更多