Vue-tables-2中如何将自定义单元格模板函数分组复用?
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

