首页 > 解决方案 > 如何将 vue-router 链接添加为 ag-grid-vue 列?

问题描述

来自 ag-grid 网站的 ag-grid-vue 文档清楚地表明:

您可以在 Grid 中提供 Vue Router 链接,但您需要确保为正在创建的 Grid 组件提供 Router。

带有示例代码:

// create a new VueRouter, or make the "root" Router available
import VueRouter from "vue-router";
const router = new VueRouter();

// pass a valid Router object to the Vue grid components to be used within the grid
components: {
    'ag-grid-vue': AgGridVue,
    'link-component': {
        router,
        template: '<router-link to="/master-detail">Jump to Master/Detail</router-link>'
    }
},

// You can now use Vue Router links within you Vue Components within the Grid
{
    headerName: "Link Example",
    cellRendererFramework: 'link-component',
    width: 200
}

这里缺少的是如何使“根”路由器可用。我一直在寻找各种来源,看到很多人有同样的问题,但没有一个得到明确的答案。

https://github.com/ag-grid/ag-grid-vue/issues/1

https://github.com/ag-grid/ag-grid-vue/issues/23

https://github.com/ag-grid/ag-grid-vue-example/issues/3

https://forum.vuejs.org/t/vue-cant-find-a-simple-inline-component-in-ag-grid-vue/21788/10

ag-grid-vue 是否仍可与 vue-router 一起使用,那么如何使用,或者这只是过时的文档?有些人声称它对他们有用,所以我认为它在某一时刻有效。

在这一点上,我不是在寻找很酷的答案。我只是想知道这是否可能。我尝试使用 window 或 created() 传递路由器,但到目前为止都没有工作。

谢谢!

标签: vue-routerag-grid

解决方案


@thirtydot 建议的方法效果很好。唯一的缺点是用户无法右键单击,但我发现您可以定义 href 链接。因此,当您左键单击时,事件侦听器会使用路由器。当您右键单击并在新选项卡中打开时,浏览器会获取 href 链接。

您仍然需要使您的根路由器可用。下面的代码示例假设您在 vue-router-aware Vue 组件中拥有使用 ag-grid 的代码,因此 this.$router 指向根路由器。

{
    headerName: 'ID',
    field: 'id',
    cellRenderer: (params) => {
        const route = {
          name: "route-name",
          params: { id: params.value }
        };

        const link = document.createElement("a");
        link.href = this.$router.resolve(route).href;
        link.innerText = params.value;
        link.addEventListener("click", e => {
          e.preventDefault();
          this.$router.push(route);
        });
        return link;
    }
}

推荐阅读