You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue-tables-2中如何将自定义单元格模板函数分组复用?

Answer

Absolutely, this is totally feasible—you just need to adjust how you structure your template functions since vue-tables-2 expects the templates option to be a flat object of key-value pairs (where keys are column names and values are the template functions).

Your current approach uses an array of individual objects, which won't work because you're passing the entire array as a single property in the templates object instead of expanding the functions into it. Here's how to fix it:

1. Define your reusable templates as a single object

Instead of an array of objects, group all your template functions into one object:

const customTemplates = {
  user_id(h, row) {
    return row.id;
  },
  user_name(h, row) {
    return row.name;
  },
  created_at(h, row) {
    return this.formatDate(row.created_at);
  }
};

2. Merge this object into your templates option

Use ES6 object spread syntax (...) to flatten the reusable templates into the templates object. This lets you combine your shared templates with any column-specific templates you might want to add:

templates: {
  ...customTemplates,
  // Optional: Add one-off templates here
  // status(h, row) { return row.status === 'active' ? '✅' : '❌'; }
}

If you need multiple template groups

If you want to split templates into separate groups (e.g., user-related, date-related), you can merge multiple objects together with either spread syntax or Object.assign:

// Separate template groups
const userTemplates = {
  user_id(h, row) { return row.id; },
  user_name(h, row) { return row.name; }
};

const dateTemplates = {
  created_at(h, row) { return this.formatDate(row.created_at); },
  updated_at(h, row) { return this.formatDate(row.updated_at); }
};

// Merge them into templates
templates: {
  ...userTemplates,
  ...dateTemplates
}

// Or using Object.assign (works in older environments)
templates: Object.assign({}, userTemplates, dateTemplates)

Why your original code didn't work

Your custom_template array was an array of single-property objects, and { custom_templates } is shorthand for { custom_templates: custom_templates }—meaning you were adding a single key custom_templates to the templates object with the array as its value. vue-tables-2 couldn't map this to your column names, hence no templates were applied.

Note about this context

Since your created_at template uses this.formatDate, make sure you use regular function syntax (not arrow functions) for your template methods. Arrow functions would bind this to the outer scope instead of your Vue component instance, breaking access to this.formatDate.

内容的提问来源于stack exchange,提问作者Theo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:44:44