如何在AG Grid单元格组件的字符串中使用MDI图标并正常显示?
Ah, I see the root issue here! The string you're returning uses Vue's interpolation syntax ({{ mdiPencil }}), but AG Grid doesn't compile that Vue template for you—it just renders the raw text. That's why you're seeing the literal {{ mdiPencil }} instead of the actual icon. Let's walk through a couple of straightforward solutions to get this working:
Solution 1: Direct SVG Path Injection (Simplest Approach)
Since @mdi/js exports raw SVG path data, you can skip Vuetify's v-icon component entirely and build an SVG element directly in your returned string. AG Grid will render this raw SVG correctly without needing Vue compilation:
import { mdiPencil } from "@mdi/js"; data() { return { mdiPencil }; }, methods: { viewButton() { return `<button style="border: none; background: transparent; cursor: pointer; padding: 0;"> <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"> <path d="${this.mdiPencil}" /> </svg> </button>`; }, }
You can adjust the width, height, or styling to match your app's design system.
Solution 2: Use a Vue Component as Cell Renderer (Vuetify-Friendly)
If you want to stick with Vuetify's v-btn and v-icon components, you need to create a dedicated Vue component for AG Grid to render (instead of returning a raw string). This is the more "Vue-native" way to handle cell content:
Step 1: Create a Cell Component
Make a new file called GridEditButton.vue:
<template> <v-btn icon> <v-icon>{{ mdiPencil }}</v-icon> </v-btn> </template> <script> import { mdiPencil } from "@mdi/js"; export default { data() { return { mdiPencil }; } }; </script>
Step 2: Register the Component in AG Grid
In your main grid component, import and register the cell renderer with AG Grid:
import GridEditButton from './GridEditButton.vue'; // Your AG Grid column configuration columns: [ { headerName: 'Actions', field: 'id', cellRenderer: 'gridEditButton', frameworkComponents: { gridEditButton: GridEditButton } } ]
AG Grid will now properly compile the Vue component, and the v-icon will resolve the MDI path correctly.
Either of these methods will fix the issue—pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者sheetaldharerao

